wookiee
wookiee

Reputation: 110

Purpose of property with empty set get

Can someone tell me, what is the porpose of using a public property for a private class member but not implementing anything in the set and get part? I know that it could be just for examples and that later on you can implement something but I don't know if there is any meaning using it like that

Upvotes: 0

Views: 6185

Answers (3)

JTW
JTW

Reputation: 3685

This is an "auto-implemented" property in C#. In effect, the property acts as a full property, i.e.:

This:

public int Number { get; set; }

Is equivalent to:

private int _number;

public int Number
{
    get
    {
        return this._number;
    }
    set
    {
        this._number = value;
    }
}

This prevents you from having to type out the full property declaration. This is useful when you don't have any additional logic in the getter and/or setter.

If you're creating simple data mapping and transfer classes, auto-implementing properties can make the class definition far more concise.

Upvotes: 3

CodingYoshi
CodingYoshi

Reputation: 27009

I am going to assume you know there is a private field generated by the C# compiler as the field backing up this property. It is syntactic sugar. I am also going to assume you know this is an auto-implemented property. So what is the point of a property if it public with no logic in the get or set. In other words, any class can access it and set its value. So why choose this property over a public field?

Purpose of it is:

  1. Today the get and set is empty but it may need code in the future. To avoid breaking a contract in the future, you use an empty get and set.
  2. Most .NET databinding can be done against properties but not fields. So although it is empty, it still serves a far greater purpose.
  3. The get and set can have access modifiers. For example, you can say set is private but get is public.
  4. A field cannot be used in interfaces but properties can.

Upvotes: 6

jdphenix
jdphenix

Reputation: 15425

When you see

public int Count { get; set; }

as a member of a class, that is not nothing. You're just deferring to the default implementation of auto-properties. It's roughly,

private int _count; 

public int get__Count() 
{
    return _count;
}

public void set__Count(int value) 
{
    _count = value;
}

You just have syntactic sugar in C# to use these methods roughly like a field, i.e.

instanceOfObject.Count = 42; // Not a field access, but behind the scenes a method call.

Upvotes: 2

Related Questions