Tuesday, June 19, 2012


Source Code Properties Project

Properties are used as an alternative for the Get and Set methods that a lot of classes have. This only involves the Get and Set methods where the Set method only has one parameter, but no data to return and where the Get method has no parameters, but does have data to return. In C# it's common that these Get/Set methods are all replaced by properties.

As usual; start by creating a new console application and call it: Properties Tutorial. Add a class to the project called: Person. First I would like to show you what the application looks like with Get and Set methods and then replace them with a property.

Add the following code to the Person class:
private string _name;
public void SetName(string name)
_name = name;
public string GetName()
return _name;

Once you've done that, add the following code to your Main function in your Program class:
Person person = new Person();
Press F5 and you will see "Bob" on your console application. Next will be replacing the Get and Set methods with a property.

Replace the Get and Set methods with the following code:
public string Name
get { return _name; }
set { _name = value; }
Now you replaced the Get and Set methods with a property. The get property accessor is used to return the value of the global _name variable, and the set property accessor is used to assign a new value to the global _name variable. Value is a keyword within C# that indicates the value/data when you call the set property accessor. So instead of a parameter, value is used.

As you can see; the get property accessor contains the code of the GetName() method and the set property accessor contains the code of the SetName(string name) method.

You also have to change the code in your Program class.

Replace the code in the Program class file with the following:
Person person = new Person();
person.Name = "Bob";
Only the way of approaching the data has changed: person.Name = "Bob" accesses the set property accessor and Console.Write(person.Name) accesses the get property accessor of the Name property. You can remove a property accessor if you want to make it read-only or set-only.

Make a global variable public and you can approach it the same way as you approach a public property with a Get and a Set accessor, so why not just use a global variable? That's because it is common to only use global variables within its own class and the same reason why all global variables are private in professional software.

Press F5 to check if the code is correctly implemented.

Source Code Properties Project

No comments:

Post a Comment