views:

545

answers:

6

What are the benefits of only using public properties instead of using the public property to access a private variable?

For example

public int iMyInt { get; set; }

instead of

private int myint;
public int iMyInt { get { return myint; } set { myint = value; } }

Other than letting .NET manage the variable / memory underneath the property, what are the advantages (or disadvantages for that matter)?

+10  A: 

Using automatic properties (the first example) requires less typing.

It is highly recommended to have only public properties and not public fields. Many properties are simple wrappers around private fields. Automatic properties save you the time and hassle of manually creating the property and backing field.

The actual code behind automatic and manual properties for the simple case you mentioned should be nearly identical.

Michael
Also advantageous to use public properties if you want to take advantage of DataBinding also
RobS
+1  A: 

There is no difference one way or the other until you want something to happen when a property is got or set.

For instance, if you want a OnMyIntSet event, you could not use the automatic property syntax.

Bob
+4  A: 

The two will be nearly identical once compiled to IL.

My rule of thumb, personally, is to use automatic properties. They are more concise, and require less typing, and I know that, when I use them, they're meant to just be a simple wrapper with no logic.

If I later need to add logic, it's easy to switch to my own backing field, and there are no (external) consequences.

Reed Copsey
+8  A: 

I'd suggest that more important than requiring less typing is the increased readability of your code. I would generally advise using automatic properties as my default option, and only switching to explicit properties if there is a particular requirement for them.

Richard
+1, Excellent point. Properties with their backing fields easily results in a lot of boiler plate code that distracts from the "important" parts of your class.
Michael
+1  A: 

My personal preference is for automatic properties unless otherwise necessary.

The advantage of using automatic properties is, of course, succinctness. It takes less room, it's easier to read, it's easier to type.

The disadvantage is that you no longer have access to the private backing variable, and sometimes you need that.

So: when you need to use the private backing variable, use the "old" method. When you don't, use an automatic property. Never use a public field. That's just crazy-talk.

Randolpho