getter and setter for class in class c#

DummyCSharp picture DummyCSharp · May 11, 2009 · Viewed 72.2k times · Source

Assuming we have a class InnerClass with attributes and getter/setter. We also have a class OuterClass containing the InnerClass.

e.g.

class InnerClass
{
    private int m_a;
    private int m_b;

    public int M_A
    {
        get
        {
             return m_a;
        }
        set
        {
             m_a = value;
        }
     }
}

class OuterClass
{
    private InnerClass innerClass
}

How would I implement a correct getter and setter for the innerClass member of OuterClass?

Thanks in advance!

Answer

Adam Robinson picture Adam Robinson · May 11, 2009

The syntax wouldn't be any different. Just...

public InnerClass InnerClass
{
    get { return innerClass; }
    set { innerClass = value; }
}

By the way, if you're using C# in .NET 3.5, you can use the automatic property generation feature if all you have is a simple property that just reads and writes to a backing store (like you have above). The sytax is similar to that of an abstract property:

public InnerClass InnerClass { get; set; }

This automatically generates a private member for storage, then reads from it in the get and writes to it in the set.