Friday 24 August 2012

Get And Set Property

Definition:
         public class MyClass
{
    private int _age;

    public int Age
    {
          get{ return _age;  }
          set{ _age = value; }
    }
}
Uses:

  • You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member.
  • You want to avoid the performace hit of going through the get or set and just use the member directly - in this case, I'd be suprised if there really was a performace hit. The simple get/set members are very very easy to inline, and in my (admitly limited) testing I haven't found a difference to using the automatic properties vs accessing the member directly.
  • You only want to have public read access (i.e. just a 'get') and the class write to the member diectly - in this case, you can use a private set in your automatic property. i.e.
    public class MyClass
    {
        public int Age {get; private set;} }
This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties.
Example Program :

using System;

class Example
{
    int number;
    public int Number
    {
 get
 {
     return number;
 }
 set
 {
     number = value;
 }
    }
}

class Program
{
    static void Main()
    {
 Example example = new Example();
 example.Number = 5; // set { }
 Console.WriteLine(example.Number); // get { }
    }
}
OutPut:
       5

No comments:

Post a Comment