53

I'm a bit confused on the point of Automatic properties in C# e.g

public string Forename{ get; set; }

I get that you are saving code by not having to declare a private variable, but what's the point of a property when you are not using any get or set logic? Why not just use

public string Forename; 

I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?

hyde
  • 2,383
  • 3
  • 19
  • 45
Gavin
  • 15,943
  • 18
  • 60
  • 106
  • 1
    possible duplicate of [Difference between Property and Field in C# .NET 3.5+](http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-net-3-5) – nawfal Jun 03 '13 at 17:03

11 Answers11

118

Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface). Properties can be read only or write only, fields can't. Properties can be data bound, fields can't.

Robert Harvey
  • 168,684
  • 43
  • 314
  • 475
MatthewMartin
  • 29,993
  • 30
  • 102
  • 160
  • You have to put your own backing field. Automatic properties let you not worry about that now, but still plan for the future, though - see my answer for details. – Reed Copsey Aug 18 '09 at 15:38
  • 4
    @Gav, Automatic properties are simple, and dumb. To add logic, you would have to turn it into a normal property. Either both get and set are automatic, or neither are. – Nader Shirazie Aug 18 '09 at 15:38
  • +1 I've heard a lot of explanations, and this one is by far the clearest. – Robert Harvey Aug 18 '09 at 15:40
  • ok just to make sure I got this right, automatic properties are pretty much a placeholder giving you the option to remove them at some point and replace them with a property? – Gavin Aug 18 '09 at 15:42
  • Automatic properties are first-class properties that can have logic added to them later without breaking the interface. They are a convenience that allows you to define the property without having to also define a backing field. – Robert Harvey Aug 18 '09 at 15:47
  • @Gav: Pretty much. They also allow more options with Databinding than fields (since they're properties), and give finer grained access control than fields. – Reed Copsey Aug 18 '09 at 15:47
  • 1
    It also becomes a control issue. By letting a field get set by any code anywhere, the class module doesn't have control and cannot know what value a field might have. That can make errors more difficult to find and can even create difficult to reproduce and find bugs. – Jeff Siver Aug 18 '09 at 15:47
15

You can write

public string Forename{ get; private set; }

to get read-only properties... Still not nearly as versatile as real properties, but it's a compromise that for some works.

Sklivvz
  • 28,698
  • 24
  • 111
  • 164
12

I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?

In the first case, the compiler will automatically add a field for you, and wrap the property. It's basically the equivalent to doing:

private string forename;
public string Forename
{
    get
    { 
        return this.forename;
    }
    set
    {
        this.forename = value;
    }
}

There are many advantages to using properties over fields. Even if you don't need some of the specific reasons, such as databinding, this helps to future-proof your API.

The main problem is that, if you make a field, but in v2 of your application, need a property, you'll break the API. By using an automatic property up front, you have the potential to change your API at any time, with no worry about source or binary compatibility issues.

Reed Copsey
  • 522,342
  • 70
  • 1,092
  • 1,340
6

It is meant that you expect to add the logic later.

If you do so and have it as property from the beginning, you will not have to rebuild the dependent code. If you change it from a variable to a property, then you will have to.

  • 2
    This is not correct. It is not meant that you expect to add the logic later. There is no intention of this inferred anywhere. It is literally just shorthand to make writing the proper code (property vs. field) easier to do. – Charles Boyung Jun 10 '10 at 15:31
4

Consider looking at some related threads about Difference Between Automatic Properties and Public Fields, Fields vs Properties, Automatic Properties - Useful or Not?, Why Not to Use Public Fields.

Community
  • 1
  • 1
Nathan Taylor
  • 23,720
  • 17
  • 90
  • 152
2

Public data members are evil (in that the object doesn't control modification of it's own state - It becomes a global variable). Breaks encapsulation - a tenet of OOP.

Automatic properties are there to provide encapsulation and avoid drudgery of writing boiler plate code for simple properties.

public string ID { get; set;}

You can change automatic properties to non-automatic properties in the future (e.g. you have some validation in a setter for example)... and not break existing clients.

string m_ID;
public string ID
{
   get { return m_ID; }
   set 
   { 
     //validate value conforms to a certain pattern via a regex match
     m_ID = value;
   }
}

You cannot do the same with public data attributes. Changing a data attribute to a property will force existing clients to recompile before they can interact again.

Gishu
  • 126,803
  • 45
  • 214
  • 298
  • 1
    That's true to an extent but OTOH public properties aren't much better than public data, at encapsulating: a tenet of OOP is "tell don't ask", whereas using properties (to get an object's internal state) is still asking rather than telling. – ChrisW Aug 18 '09 at 15:40
  • 2
    Well... I'd beg to differ, IMO public properties are much better than global variables. Tell don't ask - I take it as a heuristic for good OO design ; there are exceptions of course e.g. if it's a class that is tasked with polling n devices and exposing an overall status. It's job is to compute and convey the latest status - and you'd have to 'ask', diff clients may take diff actions based on the status. A DAL would also need ask-methods. – Gishu Aug 18 '09 at 16:07
1

A property is like a contract, and you can change the implemenation of a property without affecting the clients using your classes and properties. You may not have any logic today, but as business requirements change and if you want to introduce any code, properties are your safest bet. The following 2 links are excellent c# video tutorials. The first one explains the need of properties over just using fields and the second video explains different types of properties. I found them very useful.

Need for the Properties in C#

Poperties in C#, Read Only, Write Only, Read/Write, Auto Implemented

1

For one, you can set the property to virtual and implement logic in an inheriting class. You can also implement logic in the same class afterwards and there won't be side-effects on any code relying on the class.

1

When adding auto properties the compiler will add get set logic into the application, this means that if you later add to this logic, and references to your property from external libraries will still work.

If you migrated from a public variable to a property, this would be a breaking change for other libraries that reference yours - hence, why not start with an auto property? :)

MattH
  • 3,867
  • 2
  • 27
  • 32
1

Not all properties need get/set logic. If they do, you use a private variable. For example, in a MV-something pattern, your model would not have much logic. But you can mix and match as needed.

If you were to use a field like you suggested in place of a property, you can't for example define an interface to describe your class correctly, since interfaces cannot contain data fields.

user29117
  • 87
  • 2
0

Take a look at the following code and explanation.
The most common implementation for a property is getter or a setter that simply reads and writes to a private field of the same type as a property. An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates a private backing field.
Look into the following code:-

    public class Stock 
    {
      decimal currentPrice ;  // private backing field.
      public decimal CurrentPrice 
      {
        get { return currentPrice ; }
        set { currentPrice = value ; }
      }
   }

The same code can be rewritten as :-

   public class Stock
   {
     public decimal CurrentPrice { get ; set ; } // The compiler will auto generate a backing field.
   }

SOURCE:- C# in a Nutshell

Pratik Singhal
  • 5,566
  • 7
  • 48
  • 88