Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# , Difference between property with variable and without variable [duplicate]

Possible Duplicate:
What's the difference between encapsulating a private member as a property and defining a property without a private member?

I know the basic functionality of properties . But as i go through documentation in depth i see they are declared just with get set and without a variables .

what is the diffeence between these two

public int EmpCode
{
    get { return _strEmpCode; }
    set { _strEmpCode = value; }
}  

and

public int EmpCode
{
    get; 
    set; 
}  

Is it just a easier way of writing which got as .net frameworks got upgraded . Or is there any functional difference ?

like image 731
Kuntady Nithesh Avatar asked Sep 06 '11 05:09

Kuntady Nithesh


2 Answers

The later is called an Automatic Property and is the same.They were introduced in C#3, you can read more about them here: http://trashvin.blogspot.com/2008/05/automatic-properties-and-object.html

Simply put, Automatic Properties are syntactic sugar so the developer has to type less code and the compiler will generate the private field and the public setter and getter for you.

like image 102
Paul Avatar answered Oct 13 '22 01:10

Paul


This is called an automatic property. There is no functional difference. The latter syntax is just a shorthand of the former.

Section 10.7.3 of the C# specification gives more detail:

When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backing field.

The following example:

public class Point {
   public int X { get; set; } // automatically implemented
   public int Y { get; set; } // automatically implemented
}

is equivalent to the following declaration:

public class Point {
   private int x;
   private int y;
   public int X { get { return x; } set { x = value; } }
   public int Y { get { return y; } set { y = value; } }
}
like image 20
vcsjones Avatar answered Oct 13 '22 00:10

vcsjones