0

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?

Marcus L
  • 4,030
  • 6
  • 34
  • 42

4 Answers4

4

Heres a link you may find useful.

Community
  • 1
  • 1
Brandon
  • 68,708
  • 30
  • 194
  • 223
  • 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 Apr 08 '09 at 14:10
  • 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 Apr 08 '09 at 14:27
3

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • if I remember correctly, SOAP formatting with WCF is also affected. – DK. Apr 08 '09 at 15:43
  • WCF normally uses DataContractSerializer, which won't be affected - SoapFormatter is deprecated, but yes: suffers the same as BinaryFormatter. – Marc Gravell Apr 08 '09 at 19:26
0

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
  • 2,453
  • 6
  • 41
  • 53
0

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
  • 3,650
  • 1
  • 19
  • 19