1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - An Object Oriented Approach to Programming

By David Bolton, About.com

4 of 10

What is a Property?

What is a Property?

A property is like a public class member and allows controlled access to the internal state of an object through fields and methods within that object.

Methods are functions that change the state of an object, sort of like controls on a TV. An on/off switch enables or disables a TV, and the volume control changes the volume level of the TV and is often displayed on screen analogous to a read only property. You'll often find this- a method alters the object state and you can view the state through a read only property. On a TV, the channel selector is one of the few properties that you can actually write to.

Example of read/Write property.

public bool LastSegment
{
  get { return lastSegment; }
  set { lastSegment = value; }
}
In C# you can have properties that are read only or read/writeable. Each property has one or two functions. One is called get, the other set. Without a set function the property is read only eg Length on the previous page. Where there is no get function- it's a write only property.

Using a public field instead of a property is possible but you don't normally change the volume on a TV with a screwdriver as it is potentially lethal! If you change a class, perhaps removing a field then you could break external code. But implement it with a property and you can change the internal code in the get/set functions without breaking any external code.

Using property methods also gives tremendous flexibility when designing classes. You can place a lot of code inside the get and set methods so that what looks like a simple assignment to a property is doing a lot of work behind the scenes. That increases the overall robustness and reliability of your application and your code will look cleaner and simpler.

On the next page : About Pascal and Camel Case

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. What is a Property?

©2009 About.com, a part of The New York Times Company.

All rights reserved.