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!
It depends on how the inner class should work. The outer class might need to "own" the inner class, in which case:
By doing it this way, you prevent outside code from manipulating the instance unless explicitly through OuterClass..
If you mean accessing inner class members without exposing the inner class itself, you can use the following code. If you just want to expose
this.innerClass
, there is no difference to the way you expose the fields ofInnerClass
.The most elegant way of doing this is to use implicit getters and setters:
This is implicitly the same as:
These two definitions are implicitly the same - minus quite a few keystrokes. In the first example, the compiler will implement the necessary private fields behind the scenes so you don't have to. The second, however gives you more control of what is going on.
The syntax wouldn't be any different. Just...
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:
This automatically generates a private member for storage, then reads from it in the
get
and writes to it in theset
.