views:

84

answers:

3

Possible Duplicates:
Properties vs Methods
C#: Public Fields versus Automatic Properties

  • What is the real purpose of get,set properties in c#?
  • Any good ex when should i use get,set properties...
+1  A: 

The purpose of properties is called Encapsulation. The methods of a class should be responsible for maintaining a correct object-state. If you exposed public fields instead of properties your object would have no control over their values.

Henk Holterman
+1  A: 

Did you mean just properties or the keywords get; set;?

Properties: to put it easily, properties are smart fields. Smart being you can add logic when you want to get or set the value. Usage example: if you want to validate the values being set to a property or if you want to combine values from different fields without exposing those fields to the public.

The keywords: this is a C# shorthand to create a property with a backing field (the field that stores the values). It's useful when you're starting a new code and wanted to do the interface as early as possible.

Adrian Godong
+1  A: 

you need them to have control over your object private fields values. for example if you don't wanna allow nulls or negative values for integers. Also, encapsulation is useful for triggering events on change of values of object members. Example

  bool started;
    public bool Started
    {
        get { return started; }
        set
        {
            started = value;
            if (started)
                OnStarted(EventArgs.Empty);
        }

    }

another example

    int positiveNumber;

    public int PositiveNumber
    {
        get { return positiveNumber; }
        set {
            if (value < 0)
                positiveNumber = 0;
            else positiveNumber = value;
        }
    }

and also another implementation of read only properties could be as follows

    int positiveNumber;

    public int PositiveNumber
    {
        get { return positiveNumber; }

    }
Mustafa A. Jabbar