0

I've been learning C# out of books recently and after explaining properties I notice them using properties like

public int AlertLevel { get; private set; }

and I can't figure out why you would do this without passing any arguments? Thanks for any info in advance.

2
  • Note the key word "private", changing the scope of what can set the property. Commented Nov 26, 2014 at 21:59
  • You very rarely want to pass arguments to a property. Maybe you're not clear on what properties are actually for? Commented Nov 26, 2014 at 22:00

4 Answers 4

3

Properties are actually methods in C#. And what you have shown in the code is an auto-implemented property. It's a sytantic sugar for this:

// this backing field is generated by compiler
int alertLevel;

public int AlertLevel 
{
   get { return alertLevel; }
   private set { alertLevel = value; }  
}

And it's another syntactic sugar for this:

int alertLevel;

public int getAlertLevel()
{
    return alertLevel;
}
private void setAlertLevel(int value)
{
    alertLevel = value;
}

So you write less code, and you get same behaviour.That's the point.Compiler does the hard work for you.

Sign up to request clarification or add additional context in comments.

Comments

0

They're called auto-properties. It's syntactic sugar.

It's the equivalent of:

private int alertLevel;
public int AlertLevel
{
  get { return alertLevel; }
  private set { alertLevel = value; }  
}

It allows the value to be accessed from other classes, but only set from within the class.

1 Comment

You're right. I was thinking how you'd just set the backing field directly, but you're right there's a distinction here and reasons you'd want to do it through the property instead (e.g. use of INotifyPropertyChanged).
0

This is done to declare the element as an editable property with accessibility settings, hence the private declaration on set. You can explicitly set get; and set; on any accessible property as well with the same effect. This is simply a quicker way to type the full getter-setter relationship.

Comments

0

The example you listed is actually pretty handy. If you don't want other classes being able to modify this property, this is a lot easier than:

private int alertLevel;
public int AlertLevel
{
    get
    {
        return alertLevel;
    }
}

The other thing is the Designer view will recognize properties and expose them in IntelliSense.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.