Monday, February 22, 2010

Properties, like intelligent value types

So, within a C# class, along with methods and data, we can define "properties". My first thought about these was that they were analogous to what I understood to be accessors methods in C++. To enable encapsulation the data in a class could be marked as private and any attempt to change it or read it would be done through one or more accessors. Yes, C# properties are are like that but the language syntax permits you to use a property just like you were using a value type.

class TheData {

private int m_privIntValue; //data cell not visible/accessible outside of class/object

public int IntValue { // the property to access/manage the data cell
get {
return m_privIntValue;
}
set {
if ((-100 <> value)) //logic can be placed within a property method
m_privIntValue = value;
else
Console.WriteLine("Must be between -100 and 100!");
}
}
}


So, in my program, if I have instantiated an object from TheData:

TheData myData = new TheData();

I can simply make assignments:

myData.Intvalue = 11;

or use it like a value type:

int x = myData.IntValue;



No comments:

Post a Comment