MorkaLork Development

Interesting stuff I've picked up over the years...

Properties

2009-04-16 17:55:01 | 197 views | properties fields get set

The Basics




Setting object properties in C# can be quite handy. Properties are just data that is set one way or the other when handling classes, and the easiest way to handle them are to use the GET and SET methods to access the data.

Getting into it




Now, if you have a property called X in a class and you want to both be able to set it's value and use it, here's one way to do it:



private int X;

public int setX(int y)
{
x = y;
}

public int getX()
{
return X;
}


You'll use the setX method to set the value of the property X and getX to return the value. You can however do this in the same method with the GET/SET methods, like this:



public class myClass
{

private int X;

public int varX
{
get
{
return X;
}
set
{
X = value;
}
}

}


The GET method means that it returns the value of X and the SET method sets the value of X.
The keyword value seen in this example is used automagically in the SET method and contains the value used when calling the varX method.
It's used like this:



myClass mC = new myClass();

mC.varX = 4;

Console.WriteLine(mC.varX);
Console.Read();


The method varX now contains a means to set the variable X and to get the variableX. This saves us alot of code compared to the first example (having two differant methods) and it makes the code easier to read.

Another example:



public class Penn
{

private int height;
private string color;

public int PennHeight
{
get
{
return height;
}
set
{
height = value;
}
}

public string PennColor
{
get
{
return color;
}
set
{
color = value;
}
}

}


And we use it like this:



public static void Main(string[] args)
{
Penn bigBluePenn = new Penn();
Penn bigRedPenn = new Penn();

bigBluePenn.PennColor = "Blue";
bigBluePenn.PennHeight = 10;

bigRedPenn.PennColor = "Red";
bigRedPenn.PennHeight = 7;



Console.WriteLine("I have two pencils:");
Console.WriteLine("My first penn is {0} and its height is {1} cm", bigBluePenn.PennColor, bigBluePenn.PennHeight);
Console.WriteLine("My second penn is {0} and its height is {1} cm", bigRedPenn.PennColor, bigRedPenn.PennHeight);
Console.Read();

}


and the result will look like this:

imagehttp://morkalork.com/images/screenshots/GETSET1.jpg

First we use the SET method to set the colors and heights of the pencils, then we use the GET method when we want to output the result (thus getting the results from the pennclass).

Misc



When setting a variable in a class to static the value of that variable will keep it's value until changed. Otherwise the value will be reset to default when the class is closed.


Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.