views:

5710

answers:

22

I am used to create my Properties in C# using a private and a public field:

private string title;
public string Title
{
    get { return title;  }
    set { title = value;  }
}

Now, with .net 3.0, we got auto-properties:

public string Title { get; set; }

I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving 5 lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.

In fact, the hidden private field does not even show up in the Debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.

I see the benefit that I save a lot of code (1 vs 6 lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.

So, what am I missing here? Why would anyone actually want to use auto-properties?

+18  A: 

I personally love auto-properties. What's wrong with saving the lines of code? If you want to do stuff in getters or setters, there's no problem to convert them to normal properties later on.

As you said you could use fields, and if you wanted to add logic to them latter you'd convert them to properties. But this might present problems with any use of reflection (and possibly elsewhere?).

Also the properties allow you to set different access levels for the getter and setter which you can't do with a field.

I guess it's the same as the var keyword. A matter of personal preference.

Ray
+23  A: 

The three big downsides to using fields instead of properties are:

  1. You can't databind to a field whereas you can to a property
  2. If you start off using a field, you can't later (easily) change them to a property
  3. There are some attributes that you can add to a property that you can't add to a field
lomaxx
"If you start off using a field, you can't later (easily) change them to a property", sorry but why ?
Homam
@Homam Mainly, any consumer code that uses reflection on your fields would break, since they would have to switch from using FieldInfo to PropertyInfo.
WCWedin
+43  A: 

We use them all the time in Stack Overflow.

You may also be interested in a discussion of Properties vs. Public Variables. IMHO that's really what this is a reaction to, and for that purpose, it's great.

Jeff Atwood
+4  A: 

Thanks. What are the Problems with Fields vs. Properties? I was under the impression that I could later simply convert

Public string Title;

to

private string title;
public string Title
{
    get { return title;  }
    set { title = value;  }
}

as i can still access it using MyClass.Title, but I seem to be wrong on that?

edit: Thanks Guys, I did not know that Reflection makes such a big fuzz about it, so it actually seems to be more than just syntactic sugar

Michael Stum
It is important to remember that properties are effectively syntactic sugar for method calls, ala Java getX(), setX() methods. While they are in fact first class citizens in IL, that is what they boil down to, not fields as one would at first think.
Guvante
+3  A: 

I use auto-properties all the time. Before C#3 I couldn't be bothered with all the typing and just used public variables instead.

The only thing I miss is being able to do this:

public string Name = "DefaultName";

You have to shift the defaults into your constructors with properties. tedious :-(

Orion Edwards
@Orion Edwards ~ I know this is like a dollar late and a day short, but try http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
drachenstern
@drachenstern, check out the big yellow box on that page. DefaultValueAttribute only gives you something that can be used by reflection to tell what the default value should be. It doesn't set the value for you.
Matthew Whited
@Matthew Whited ~ Good call, must not have noticed the glaring yellow box because I use the scriptfree, it blended in, but c'est la vie ...
drachenstern
+4  A: 

I think any construct that is intuitive AND reduces the lines of code is a big plus.

Those kinds of features are what makes languages like Ruby so powerful (that and dynamic features, which also help reduce excess code).

Ruby has had this all along as:

attr_accessor :my_property
attr_reader :my_getter
attr_writer :my_setter
Mike Stone
+2  A: 

The only problem I have with them is that they don't go far enough. The same release of the compiler that added automatic properties, added partial methods. Why they didnt put the two together is beyond me. A simple "partial On<PropertyName>Changed" would have made these things really really useful.

Ch00k
You can put multiple partial methods inside of another method. Creating an auto-pattern of some sort for them would be confusing.
Matthew Whited
+20  A: 

Yes, it does just save code. It's miles easier to read when you have loads of them. They're quicker to write and easier to maintain. Saving code is always a good goal.

You can set different scopes:

Public string PropertyName { get; private set; }

So you don't lose any functionality.

Keith
"So you don't lose any functionality."how do you debug them?
wal
@wal - what's there to debug? From that point of view you're basically dealing with member variables.
Keith
In the original posters example, how do you find when myObj.Title is changing from one value to another?
wal
@wal - You can put a breakpoint on them, just like you can access of a member variable, you just can't step into them. But why would you want to? What the auto-properties actually do is both trivial and auto-generated, if you've got bugs that's one place they're extremely unlikely to be.
Keith
we may need to take this outside Keith. :)
wal
But ok, assume you have many setter calls to myObj.Title...you want to see where the value changes from "text" to null, ie a conditional breakpoint. how do u acheive that? you cant even set a breakpoint on the setter
wal
A: 

One thing to note here is that, to my understanding, this is just syntactic sugar on the C# 3.0 end, meaning that the IL generated by the compiler is the same. I agree about avoiding black magic, but all the same, fewer lines for the same thing is usually a good thing.

pbh101
+1  A: 

In my opinion, you should always use auto-properties instead of public fields. That said, here's a compromise:

Start off with an internal field using the naming convention you'd use for a property. When you first either

  • need access to the field from outside its assembly, or
  • need to attach logic to a getter/setter

Do this:

  1. rename the field
  2. make it private
  3. add a public property

Your client code won't need to change.

Someday, though, your system will grow and you'll decompose it into separate assemblies and multiple solutions. When that happens, any exposed fields will come back to haunt you because, as Jeff mentioned, changing a public field to a public property is a breaking API change.

ESV
+5  A: 

Auto-properties are as much a black magic as anything else in C#. Once you think about it in terms of compiling down to IL rather than it being expanded to a normal C# property first it's a lot less black magic than a lot of other language constructs.

ICR
A: 

I use CodeRush, it's faster than auto-properties.

To do this:

 private string title;
public string Title
{
    get { return title;  }
    set { title = value;  }
}

Requires eight keystrokes total.

Brian Leahy
If I hold down CTRL and V, I can paste lots and lots of stuff, /really quickly/, but that doesn't make it 'better'. How does this answer the original question?
JBRWilkinson
A: 

Well with code snippets an auto-property of the same name would be seven keystrokes in total ;)

ICR
+5  A: 

One thing nobody seems to have mentioned is how auto-properties are unfortunately not useful for immutable objects (usually immutable structs). Because for that you really should do:

private readonly string title;
public string Title
{
    get { return this.title; }
}

(where the field is initialized in the constructor via a passed parameter, and then is read only.)

So this has advantages over a simple get/private set autoproperty.

Domenic
If you have a struct changing any property on it results in a new struct. This would only be an issue if you wanted an internally immutable reference type - I can't see a reason why you ever would need one.
Keith
@Keith: Your first sentence seems factually incorrect.
Domenic
@Domenic: I think he's confining his definition of structs to immutable ones.
maxwellb
Wouldn't `public string Title { get; private set; }` kind of result in exactly the same thing? You would be able to change it from inside the class then of course, but if you do that you have other problems... :p
Svish
The idea is defensive coding.
Domenic
A: 

@Domenic : I don't get it.. can't you do this with auto-properties?:

public string Title { get; }

or

public string Title { get; private set; }

Is this what you are referring to?

Andrei Rinea
You can (the latter; the former will not compile), but then the field is not immutable inside your object.
Domenic
Word of caution, only structs are immutable when flagged readonly, classes are just unassignable.
Guvante
+2  A: 

It's simple, it's short and if you want to create a real implementation inside the property's body somewhere down the line, it won't break your type's external interface.

As simple as that.

Omer van Kloeten
A: 

I love them. They are a real time saver for me. They also help make the code more readable in my opinion. :)

Joshua Hudson
+2  A: 

I wish Visual Studio would have an option to expand the Auto-Property. Right Click -> Refactor -> Create fields. This would make prototyping so much easier.

Jonathan C Dickinson
+1  A: 

From Bjarne Stroustrup, creator of c++:

I particularly dislike classes with a lot of get and set functions. That is often an indication that it shouldn't have been a class in the first place. It's just a data structure. And if it really is a data structure, make it a data structure.

An you know what? He's right. How often are you simply wrapping private fields in a get and set, without actually doing anything within the get/set, simply because its the "object oriented" thing to do. This is Microsoft's solution to the problem; they're basically public fields that you can bind to.

Giovanni Galbo
A: 

My biggest gripe with auto-properties is that they are designed to save time but I often find I have to expand them into full blown properties later.

What VS2008 is missing is an Explode Auto-Property refactor.

The fact we have an encapsulate field refactor makes the way I work quicker to just use public fields.

John Nolan
+3  A: 

I always create properties instead of public fields because you can use properties in an interface definition, you can't use public fields in an interface definition.

Theo
+2  A: 

wow! if someone offers you free cake you're the kind of person that asks whats in it aren't you. these are like a dream come true to me

Simon_Weaver
Yes, I do. Not much is truly free in this world, so as a developer I think it's the right thing to ask "So, are there any caveats?". It's also a sign of caring about your profession. If my customers believe in Magic that's great, but I like to do where the strings are placed.
Michael Stum