Question

If you create a property in C#, AFIK, you don't need a private backing-variable if you simply use get/set, taking advantage of C# 3.0 auto-implemented properties:

...
public int Age {get;set;}

However, let's say you want to put a touch of logic into the Age property and let it accept values only greater than 18. At this point, is it necessary to create a private variable? Is there a way around that?

Was it helpful?

Solution

However, let's say you want to put a touch of logic into the Age property and let it accept values only greater than 18. At this point, is it necessary to create a private variable?

Yes. You will need a backing field.

you don't need a private backing-variable if you simply use get/set,

For auto implemented properties, compiler will add the backing field.

See: Auto-Implemented Properties (C# Programming Guide)

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 property would look like:

private int _age;

public int Age
{
    get { return _age; }
    set
    {
        if (_age > 18)
            _age = value;
        else
        {
            //throw exception, Show message etc 
        }
    }
}

OTHER TIPS

At this point, is it necessary to create a private variable?

well, you have to store it somewhere - usually a private backing variable is easiest.

You could use validation attributes, but those are enforced at the UI layer - it does not add any "special" logic to the setter that's used universally.

BTW the compiler creates backing variables behind-the-scenes for you anyways, so it doesn't change the low-level behavior.

Yes it is necessary. No, there is no way around it.

Is there a way around that?

No, there is no way around it: if your code needs to store the state of the property in a variable, and you need some logic around that variable, you need to add that variable manually.

There are only two cases when you do not need a backing variable for a property:

  • Your property is calculated, and
  • Your property us auto-implemented.

Yes, you'll need to declare your own private backing field.

Just to be clear, when you use an auto-implemented property, there still is a private backing field, except it's generated by the compiler.

You'll need to declare it yourself if you want to add logic to the property, or if you only need either a getter or a setter, but not both.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top