views:

145

answers:

4

Are there any further benefits to the "new", shorter way to handle properties, other than shorter code - like performance benefits, less memory usage etc.?

Writing

public string StrVariable { get; set;}

Rather than

private string strVariable;

public string StrVariable
{
    set
    {
        strVariable = value;
    }
    get
    {
        return strVariable;
    }
}

And are there any drawbacks - perhaps some would argue the code is less readable, less explicit?

+4  A: 

Heres a link you may find useful.

Brandon
Thanks, I was sure someone had already asked the question, but couldn't find it. Is it just me having trouble finding things with the SO search?
Marcus L
Nope, when I search for multiple keywords there doesn't seem to be any ordering by relevance. It also makes it hard when you don't know the name of the thing you're trying to look up.
Brandon
A: 

One drawback I can see is if you want to do something else in the get/set routines. Increment a counter or something of that sort. Maybe validate the input if you haven't already.

Sean
In that scenario you would simply switch to explicit; I believe the OP is referring to the simple pass-thru case.
Marc Gravell
+3  A: 

One big drawback in a specific scenario - you lose control of the field name. This might sound insignificant, but it is a big problem if you are using binary serialization (via BinaryFormatter).

Other things:

  • they can't be readonly at the field level
  • for structs you need to call : this() in custom constructors

They do, however, do a fantastic job in 99% of cases - they express the code neatly, while leaving it possible to add extra implementation details later (by switching to explicit fields) without breaking calling code (except for the points above).

Marc Gravell
if I remember correctly, SOAP formatting with WCF is also affected.
DK
WCF normally uses DataContractSerializer, which won't be affected - SoapFormatter is deprecated, but yes: suffers the same as BinaryFormatter.
Marc Gravell
A: 

Collection properties are one issue as well. They are not initialized with Autoproperties.

Example:

public class foo
{
    public List<String> S1 { get; set; }

    private List<string> s = new List<string>();
    public List<String> S2
    {
        get { return s;}
        set { s = value; }
    }
}

foo f = new foo();
f.S1.Add("thing");
f.S2.Add("thing");

f.S1.Add will bomb with a nullref exception.

Chad Ruppert