Beginners C# Tutorial - Properties

Beginners C# Tutorial - PropertiesProperties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field. To get an appreciation for what properties accomplish, let’s take a look at how to provide field encapsulation by traditional methods.


The PropertyTester class uses the methods of the PropertyHolder class to get the value of the someProperty field in the PropertyHolder class. The Main() method instantiates a new PropertyHolder object, propHold. Next it sets the someMethod of propHold to the value 5 by using the setSomeProperty method. Then the program prints out the property value with a Console.WriteLine() method call. The argument used to obtain the value of the property is a call to the getSomeProperty() method of the propHold object. It prints out “Property Value: 5″ to the console.
This method of accessing information in a field has been good because it supports the object-oriented concept of encapsulation. If the implementation of someProperty changed from an int type to a byte type, this would still work. Now the same thing can be accomplished much smoother with properties.

Website: www.freewebs.com | Filesize: 80kb
No of Page(s): 6
Click here to download Beginners C# Tutorial - Properties.

Related Tutorial

Tags: , ,

Comments

Leave a Reply