Question

My question about set and get methods.. Although I know how to use and why it is using for, I cant understand main differences between these using styles...

public string a{get;set;} 

public string a
{
  get{return a;}
  set{a=value;}
}
Était-ce utile?

La solution 2

If you want to wite less code, use the first form, called auto property. Behind the scene, the compiler will create the backing field for you.

If you have some procesing in the property, use the standard way

public string A{get;set;} //Auto property

public string A
{
  get{return a;}`
  set{
//Do some check-Processing
    if(value != null)
       a=value;
    }
}

Autres conseils

The first form is Auto implemented properties in C#

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.

The second form (although incorrect) in current form requires a backing field explicitly defined and you can put explicit code for setting and reading the values.

Second form can be like:

private string _a; // a backing field
public string a
{
    get
    {
        return _a;
    }
    set
    {
        if (a != null) //some validation
            _a = value;
        else
            _a = string.Empty;
    }
}

(Currently your second form of property would cause a stackoverflow exception since it will enter in an infinite loop)

The first one will generate an implicit field your values will be written to and read from. These are called "auto implemented properties". Whereas in the second, you explicitly name the fields your property will write to and read from. From MSDN:

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.

Your implementation

public string a
{
  get{return a;}
  set{a=value;}
}

will cause a StackoverflowException as you are calling a recursively in the get-accessor.

Change it to

private string a;

public string A{

get{ return a; }
set{ a = value; }

}

Let's take an example :

private string _chars;

public string Chars
{
  get { return _chars; }
  set 
  { 
    DoSomeThingSpecialWhenEdited();
    _chars = value;
  }
}

Can give you a choice to trigger DoSomeThingSpecialWhenEdited or not by setting _chars or Chars

Otherwise, the two are equivalent (Note that the latter is infinite loop) .

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top