Properting and Indexing
A lot of C# code i run into does not take advantage of the easy and efficient way C# gives enable class members access. It is called indexing and properties, and they make the clients life easier, and the class's life more secure and stable.
Under the CLR, a property is the common way of exsposing a class's member access control.
A property can have a 'set' accessor and/or a 'get' accessor. when it has the get accessor only, it is a read only member, when it has the set accessor only, it is a write only member.
So far, nice story. Lets see the code:
class TheClass
{
private string m_value;
}
You can obviously state that m_value is nor readable or writable from a client code. But say we want to enable one of those or both in a smarter .nety way...
We add a public property (not necessary has the same member name) like so:
public string ClassValue
{
set
{
m_value = value;
}
get
{
return m_value;
}
}
Dont get confused by the implicit parameter named value, it holds the value given and that's all.
With set and get (or one of them) in place, we add a smart way to access our member variables through client's code:
TheClass MyClass = new TheClass;
MyClass.ClassValue = "CSharp";
String str = MyClass.ClassValue;
2nd code line calls set, and the third calls get.
In C# (as not in C/C++) indexers are not limited to arrays types only. Any type we need could be indexed. We define an index with the property named this , lets define an array of strings:
Class ArrayOfStrings
{
public ArrayOfStrings(int x)
{
m_strs = new string[x];
}
private string[] m_strs;
}
So far its just a regular class with a string array as a private member, and a constructor which sets the number of elements (strings here) in the array.
Lets use what we learned in the property section to add set and get accessors to the array (which is private):
Public string this[int index]
{
get
{
return m_strs[index];
}
set
{
m_strs[index] = value;
}
}
In the class, we enable a smart and easy way from the client point of view to access member array:
ArrayOfStrings aos = new ArrayOfStrings(10);
aos[0]="Crawler";
String str=aos[0];
And ill say it again, an indexed array in C# can be anything , even a class or struct could be used.
|
|
© Copyright
2002
Sagiv Hadaya.
Last update:
10/11/2002; 1:45:39 AM. |
|