Function that returns a link to edit in C #

Is there a way for the function to return an editable link to some internal data. Here's an example that will hopefully help 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 would return a reference or pointer.

0


source to share


4 answers


Actually, your code sample demonstrates after some cleaning that when you assign the value 37, you also change bar interman m_foo. So the answer is: your function returns a reference type. Now maybe your real code is different and it does not return a reference type but an int, a value type or a 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 on link types and types: http://www.albahari.com/valuevsreftypes.aspx

+2


source


You are already returning the link foo

in getFoo

(this is the default). Therefore, any changes you make to the return value getFoo

will be reflected in the internal data structure foo

in bar

.



0


source


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;}
    }
}

      

0


source


Exploded. I'm going to figure out how to simplify my non-working code into an example that really breaks. Sorry, nonsense.

0


source







All Articles