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!
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
.
The most elegant way of doing this is to use implicit getters and setters:
class InnerClass
{
public int a{ get; set; }
public int b{ get; set; }
}
class OuterClass
{
public InnerClass innerClass{ get; set; }
}
This is implicitly the same as:
class InnerClass
{
private int _a;
public int a
{
get
{
return _a;
}
set
{
_a = value;
}
}
private int _b;
public int b
{
get
{
return _b;
}
set
{
_b = value;
}
}
}
class OuterClass
{
private InnerClass _innerClass;
public InnerClass innerClass
{
get
{
return _innerClass;
}
set
{
_innerClass = value;
}
}
}
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.
public InnerClass InnerClass
{
get
{
return innerClass;
}
set
{
innerClass = value;
}
}
It depends on how the inner class should work. The outer class might need to "own" the inner class, in which case:
public InnerClass InnerClass{
get{ return innerClass; }
set{ innerClass.CopyFrom(value); /* Pseudo method call */ }
}
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 of InnerClass
.
class OuterClass
{
private InnerClass innerClass
public int M_A
{
get
{
if (this.innerClass != null)
{
return this.innerClass.M_A;
}
else
{
throw new InvalidOperationException();
}
}
set
{
if (this.innerClass != null)
{
this.innerClass.M_A = value;
}
else
{
throw new InvalidOperationException();
}
}
}
}