LaVOZs

The World’s Largest Online Community for Developers

'; Function which returns reference to be edited in c# - LavOzs.Com

Is there a way to have a function return a editable reference to some internal data. Here's an example I hope helps show what I mean.

class foo
{
    public int value;
}

class bar
{
    bar()
    {
       m_foo = new foo();
       m_foo.value = 42;
    }
    private m_foo;
    foo getFoo(){return m_foo;}
}

class main
{
    int main()
    {
        bar b = new bar();
        b.getFoo().value = 37;
    }
}

The return of getFoo() according to "==" is the same as the internal m_foo until I try to edit it. In c/c++ I'd return a reference or pointer.

Actually, your code sample, after some cleaning up, does demonstrate that when you assign 37 to value, you are changing bar's interman m_foo too. So the answer is, your function is returning a reference type. Now, maybe your real code is different, and it's returning not an reference type but an int, a value type, or string, a kind of special beastie...

using System;

namespace ConsoleApplication1
{
    public class foo
    {
        public int value;
    };

    public class bar
    {
        public bar()
        {
            m_foo = new foo();
            m_foo.value = 42;
        }

        private foo m_foo;
        public foo getFoo() { return m_foo; }
    };

    public class Program
    {
        public static int Main()
        {
            bar b = new bar();
            b.getFoo().value = 37;
            return 0;
        }
    };
}

More about reference vs value types: http://www.albahari.com/valuevsreftypes.aspx

You're already returning the reference of foo in getFoo (this happens by default). So any changes that you make to the return value of getFoo will be reflected in the internal foo data structure in bar.

Jeremy

You want to use a property for this

class bar
{
    private m_foo;
    bar()
    {
       m_foo = new foo();
       m_foo.value = 42;
    }


    foo Foo
    {
    get { return m_foo;}
    }
}

Blasted. I'm going to figure out how to simplified my non-working code into an example that actually breaks. Excuse me stupidity.

Related
How do I calculate someone's age in C#?
Calculate relative time in C#
What is the difference between String and string in C#?
Calling the base constructor in C#
What is the best way to give a C# auto-property an initial value?
What are the correct version numbers for C#?
What do two question marks together mean in C#?
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
Get int value from enum in C#