Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

properties in C#

Why are we able to write

public int RetInt
{
   get;set;
}

instead of

public int RetInt
{
   get{return someInt;}set{someInt=value;}
}

What is the difference between the two?

like image 721
Bé Cu Sữa 3 Avatar asked Jan 28 '13 10:01

Bé Cu Sữa 3


People also ask

What are the properties in C?

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.

What are the properties of a program?

A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field (or data member) and a method.

How do you declare a property in class?

A property may be declared as a static property by using the static keyword or may be marked as a virtual property by using the virtual keyword. Get Accessor: It specifies that the value of a field can access publicly. It returns a single value and it specifies the read-only property.


1 Answers

This feature is called Auto implemented properties and introduced with C# 3.0

In C# 3.0 and later, 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 as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

class Customer
{
    // Auto-Impl Properties for trivial get and set 
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

For your question

What is the difference between the two?

In your case, none. Since you are not doing anything while setting or retrieving the value, but suppose you have want to do some validation or want to perform other types of check then :

private int someInt;
public int RetInt
{
    get
    {
        if (someInt > 0)
            return someInt;
        else
            return -1;
    }
    set { someInt = value; } // same kind of check /validation can be done here
}

The above can't be done with Auto implemented properties.

One other thing where you can see the difference is when initializing a custom class type property.

If you have list of MyClass Then in case of Normal property, its backing field can be initialized/instantiated other than the constructor.

private List<MyClass> list = new List<MyClass>();
public List<MyClass> List
{
    get { return list; }
    set { list = value; }
}

In case of Auto implemented property,

public List<MyClass> SomeOtherList { get; set; }

You can only initialize SomeOtherList in constructor, you can't do that at Field level.

like image 129
Habib Avatar answered Sep 24 '22 13:09

Habib