C# Custom getter/setter without private variable

Tin Can picture Tin Can · Dec 20, 2011 · Viewed 77.4k times · Source

I learned c# recently, so when I learned to write properties, I was taught to do it like this:

public string Name { get; set; }

Auto properties are great! But now I'm trying to do something a little more complicated, so I need to write a custom pair of accessors.

private string _Name;
public string Name {
    get { return _Name; }
    set { _Name = value }
}

I know the compiler makes a private instance variable down in it's murky depths when one uses autos, but I'm spoiled and don't want that private variable sitting around looking pointless.

Is there a way to use custom accessors without a private variable?

Answer

jhappoldt picture jhappoldt · Dec 20, 2011

Properties don't need backing variables (fields) at all. While they can be used for encapsulating simple fields you can also use them to access other data.

public Decimal GrandTotal { get { return FreightTotal + TaxTotal + LineTotal; } }

or

public string SomeStatus { get { return SomeMethodCall(); } }

If the goal is to simply encapsulate some field with a property you would need some sort of backing field if you are not using automatic properties.