2

Possible Duplicate:
Difference between Property and Field in C#

I started a new job a couple of weeks ago using C# (something I've basically started learning -since- being there) and I've seen a couple of ways of doing things and I'm curious why (seeing as I'm leaning fresh and they've all picked up stuff over the years.)

Basically, I'm trying to figure out why:

private int i;

Is better than:

private int I {get;set;}

If the answer is (as I suspect) that extra IL is generated for calling the get/sets, then why do the autoimplemented get/sets exist at all? Why is

public int i;

Worse than:

public int I{get;set;}

More curious that anything else why I wouldn't just always use properties, or why I wouldn't avoid the autoimplemented methods like the plague, one or the other.

I know this sounded like a logical question when I thought of it, but not so much when I wrote it, so I hope it makes some kind of sense.

Thanks

Community
  • 1
  • 1
user1217210
  • 113
  • 5
  • Generally, you *would* always use properties. I think that's the answer to your question, or at least the one you should be seeking. As for why they exist at all, consider that properties are implemented under the hood with a private field, so private fields *have* to be supported in order for properties to work. It therefore wouldn't make a lot of sense to remove this capability. Furthermore, automatic properties (the shorthand syntax you show in the question) wasn't invented for C# until later, so not all that long ago, programmers had to write out all of the backing fields by hand. – Cody Gray - on strike Feb 17 '12 at 21:52
  • The reason you use properties, (your `int I {get; set;}`) is because properties is how you want the outside world to see your class. Private properties are essentially useless. The reason why you want to use public properties instead of public fields is mostly style, not just for you, but also for any programs that use reflection. – Sam I am says Reinstate Monica Feb 17 '12 at 21:53
  • this is already answered [Here][1] [1]: http://stackoverflow.com/questions/3035790/purpose-of-getters-and-setters –  Feb 17 '12 at 21:55
  • Some good reading here: http://csharpindepth.com/articles/chapter8/propertiesmatter.aspx – qxn Feb 17 '12 at 21:49

1 Answers1

1

There are many times when you need extra logic beyond what the auto-implemented properties define.

For example, if you want to implement INotifyPropertyChanged, in that case, you'll need your own backing field, so you can write:

private int someValue;
public int SomeValue
{
    get { return this.someValue; }
    set
    {
        if (value != this.someValue)
        {
            this.someValue = value;
            this.RaisePropertyChanged("SomeValue"); // This extra logic required...
        }
    }
}
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373