Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is a property which is encapsulated below:
C#
int _CategoryID;

   public int CategoryID
        {
            get
            {
                return _CategoryID;
            }
            set
            {
                _CategoryID = value;
            }
        }


and other is direct get set in the variable like :
C#
public int CategoryID { set; get; }



So my question is that , what is difference between in both and what shoud we use or recommended?
Are they same ?

please let me know about it...
Posted
Updated 2-Dec-13 1:17am
v2
Comments
bbirajdar 2-Dec-13 8:20am    
Both are same. The second one came up in c#2.0

One way lets you have validation or other code in the property set/get. The other way simply sets or gets the property with no additional code.

The Microsoft Help file explains the differences:

Using Properties (C# Programming Guide[^]
Properties have many uses: they can validate data before allowing a change; they can transparently expose data on a class where that data is actually retrieved from some other source, such as a database; they can take an action when data is changed, such as raising an event, or changing the value of other fields.

Auto-Implemented Properties (C# Programming Guide)[^]
Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
 
Share this answer
 
v3
Hi
Your first code illustrate field encapsulation with property and second code is auto property when you are use property for encapsulate field you can write some codes in property for control value before than binding to field and additionally:

1-You can`t data bind to a field whereas you can to a property
2-If you start off using a field, you can`t later (easily) change them to a property
3-There are some attributes that you can add to a property that you can`t add to a field
4-Fields can't be used in data binding (at least in some binding implementations)
5-You can add more logic later for properties without breaking source or binary compatibility
6-Properties can't be passed by reference
7-You can't add an initialization method to an automatically implemented property


Best Regards.
 
Share this answer
 
v3

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