Click here to Skip to main content
15,868,115 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
what is the difference between these statements
1.

public class Pesron

{
private string _name;
private int _age;

public string Name { get; set; }
public int Age { get; set; }
}

2.

public class Pesron
{
private string _name;
private int _age;


public string Name
{
get { return _name; }
set { _name = value; }
}

public string Age
{
get { return _age; }
set { _age = value; }
}

}
Posted

The former uses automatic properties - the _name and _age fields are not used as the compiler generates it's own backing fields.
The second version explicitly references your own backing fields.
 
Share this answer
 
Comments
__TR__ 13-Jul-12 12:27pm    
My 5!
Sander Rossel 13-Jul-12 13:33pm    
Of course :)
The first one uses the default get and set code, and you don't need to include the field variables, so you can actually write it as:

C#
public class Pesron

{
public string Name { get; set; }
public int Age { get; set; }
}


This will create _Name and _Age variables automatically when it compiles and I believe if you made variables with those names (capitalization matters!) you'd get a compile error.

The second is just the manual equivalent. If you aren't doing anything beyond getting/setting the variables, and you don't need to access the private member directly, the first is just more convenient to type.
 
Share this answer
 
Comments
Sander Rossel 13-Jul-12 13:31pm    
5'ed. Capitalization matters indeed :)
The two are identical as far as IL is concerned. Normally only use backing field if you need to do something extra in the get or set code, such as doing a NotifyPropertyChanged. Even when you want to have readonly properties you may find that the automatic properties will work because you can do something like this:

public string Name { get; private set; }
 
Share this answer
 
Comments
Sander Rossel 13-Jul-12 13:33pm    
5'ed. The IL is indeed the same for both (I recently wrote an article about it). The automatic private setter is a nice addition. As far as I know it's not possible in VB (which I use in my day-to-day job).
Rakesh S S 14-Jul-12 10:34am    
I agree
Sergey Alexandrovich Kryukov 13-Jul-12 18:39pm    
My 5.
--SA
Well Its Same thing only, The main benefit is that you are writing less code for performing the same functionality. The IL that will be generated will be the same.In Other words the compiler will put everything in place for you!
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 13-Jul-12 18:40pm    
Correct, my 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900