Search code examples
c#coding-styleaccessorautomatic-properties

C# Custom getter/setter without private variable


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?


Solution

  • 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.