Click here to Skip to main content
16,023,224 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
hi,
i have seen two types of get and set properties in C#, what is the difference between them?

public int setX {get;set;}


and

public int setX
   {
       get
       {
           return y;
       }
       set
       {
           y = value;
       }
   }


Thanks.
Posted
Updated 10-Jul-10 18:11pm
v2

1 solution

In the first version, the backing store is auto-generated by the compiler. Basically saves you some typing and gives you cleaner leaner code.

More info here: Auto-Implemented Properties (C# Programming Guide)[^]

[Edit]
----------

Adding info based on the comments: The private field is generated at compile time, so your code cannot access it. If you need to access it then you need to implement a regular property with a manually implemented backing field.
 
Share this answer
 
v3
Comments
shyam kumar1986 28-Oct-10 2:08am    
but to which private member this Property is initializing is not clear ?Actually no private member is involved here. Then ,in this way i may also take public variables too.What makes the special if we use Property in this way ?As far as i know Public Properties are used to get and set values of private members of a class.
Nish Nishant 28-Oct-10 8:35am    
The private field is generated by the compiler.
shyam kumar1986 28-Oct-10 20:47pm    
can we get that private field in that class's context ?
Nish Nishant 28-Oct-10 21:07pm    
Not sure what you mean. The field is a private member of that class. It's generated at compile time, so you cannot access it in code if that's what you mean.
Nish Nishant 28-Oct-10 21:09pm    
Gotta say I am a tad tickled that it was selected as answer and yet voted a 2. Tough world! :-)

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