66

In much of the code I have seen (on SO, thecodeproject.com and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of get; set; like:

private int myInt;
public int MyInt 
{
     get { return myInt; }
     set { myInt = value }
}

My question is: how does this differ from:

public int MyInt;

and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!

Callum Rogers
  • 15,630
  • 17
  • 67
  • 90
  • Is this really not a duplicate? – Ruben Bartelink Aug 14 '09 at 12:49
  • Hard to believe that this question wasn't asked here in SO till now! –  Dec 23 '09 at 08:32
  • It was, and i did it i think. Hang on while i hunt it down... – RCIX Feb 03 '10 at 09:05
  • 1
    Asked exactly a day before: [Property(with no extra processing) vs public field](http://stackoverflow.com/questions/1272521/propertywith-no-extra-processing-vs-public-field) :) – nawfal Jun 03 '13 at 17:32
  • *"It does not seem to add any extra encapsulation"*. Useful when debugging. Set breakpoint on "set" line. Stops on every set (but not on get). Rt-click "set" / "Find all references". Lists only the code lines that set it. – ToolmakerSteve Aug 31 '23 at 22:56

13 Answers13

35

See this article http://blog.codinghorror.com/properties-vs-public-variables/

Specifically

  • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
  • You can't databind against a variable.
  • Changing a variable to a property is a breaking change.
Johnno Nolan
  • 29,228
  • 19
  • 111
  • 160
  • 3
    Using properties is preferable to using fields because you can change the statements in the get and set blocks without needing to change the classes that depend on the property. – SKARVA Bodavula Aug 23 '16 at 10:46
25

Three reasons:

  1. You cannot override fields in subclasses like you can properties.
  2. You may eventually need a more complex getter or setter, but if it's a field, changing it would break the API.
  3. Convention. That's just the way it's done.

I'm sure there are more reasons that I'm just not thinking of.

In .Net 3.x you can use automatic properties like this:

public int Age { get; set; }

instead of the old school way with declaring your private fields yourself like this:

private int age;

public int Age
{
    get { return age; }
    set { age = value; }
}

This makes it as simple as creating a field, but without the breaking change issue (among other things).

Max Schmeling
  • 12,363
  • 14
  • 66
  • 109
  • =1: where do you get that fields cannot be serialized? – John Saunders Aug 14 '09 at 12:38
  • 2
    "You may eventually need a more complex getter or setter, but if it's a field, changing it would break the API." Not really. You can safely go from: public int Joe; to private int _joe; public int Joe { get { //do something } set { //do something } } You may have to change a lot of internal references, but that doesn't break your API. – Russell Steen Aug 14 '09 at 12:39
  • @John Saunders that's what I've read... is it not true? was it ever true? – Max Schmeling Aug 14 '09 at 12:42
  • @Russel Steen okay, maybe not break the API, but you'll have to recompile – Max Schmeling Aug 14 '09 at 12:44
  • @John Saunders: i guess it's a little true http://msdn.microsoft.com/en-us/library/ms950721.aspx – Max Schmeling Aug 14 '09 at 12:45
  • Thanks for the "public int Age { get; set; }" tip – Callum Rogers Aug 14 '09 at 12:49
  • 7
    @Russell Steen - Of course that's a breaking change. Just because it *looks* the same in C# doesn't mean it *is* the same. You're changing a field access into a method call, which is entirely different, and any calling code will need to be recompiled. – Greg Beech Aug 14 '09 at 13:17
  • @Max: First of all, what year is this? That article is six years old! Please be careful with old articles. MSDN retains all sorts of worthless information. The issue with fields is that _private_ fields cannot be serialized by XML Serialization. But XML serialization is pretty much "legacy" technology today in any case. The Data Contract Serializer has no problem with private fields. – John Saunders Aug 14 '09 at 16:28
9

When you create private field name and a simple public property Name that actually gets and sets the name field value

public string Name
{
   get { return name; }
}

and you use this property everywhere outside your class and some day you decide that the Name property of this class will actually refer to the lastName field (or that you want to return a string "My name: "+name), you simply change the code inside the property:

public string Name
{
   get { return lastName; //return "My name: "+name; }
}

If you were using public field name everywhere in the outside code then you would have to change name to lastName everywhere you used it.

agnieszka
  • 14,897
  • 30
  • 95
  • 113
7

Well it does make a difference. Public data can be changed without the object instance knowing about it. Using getters and setters the object is always aware that a change has been made.

Remember that encapsulating the data is only the first step towards a better structured design, it's not an end-goal in itself.

PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
4

You have to use properties in the following cases:

  1. When you need to serialize data in the property to some format.
  2. When you need to override properties in derived class.
  3. When you implement get and set methods with some logic. For example, when you implement Singleton pattern.
  4. When you're derived from interface, where property was declared.
  5. When you have specific issues related to Reflection.
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Pavel Podlipensky
  • 8,201
  • 5
  • 42
  • 53
3

It... depends?

I always use getters & setters, since they created this shortcut:

public int Foo { get; set; }

At compile time it is translated. Now you can't get fancy with it, but it is there, and if you need to get fancy you just spell it out later.

However public, private, protected... it's all a matter of who you want to be able to tweak the data. We use inheritance a lot and this is a very common method for us, so that only chidren can edit certain properties.

protected _foo;  
public Foo  
{  
    get { return _foo; }
} //lack of set intentional.
Russell Steen
  • 6,494
  • 6
  • 38
  • 56
1

I can't believe that with 11 answers, nobody has said this:

Not all private fields should be exposed as public properties. You should certainly use properties for anything that needs to be non-private, but you should keep as much of your class private as possible.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 2
    Reread the question - I need these private fields to be accessible from outside the class in this case. Of course you would not make every field public or give every field a property! – Callum Rogers Aug 14 '09 at 12:47
  • 1
    Actually, the question says nothing about what you need, only about what you've seen public properties being created for every private field. If you have fields that require public access, then they are not private fields, and do not match what you were asking the question about. Please edit the question to make it clear what _your_ code has in it, as opposed to the examples you've seen "on SO, thecodeproject.com" – John Saunders Aug 14 '09 at 13:07
0

There are many reasons why.

Mainly:

  • You can do some other functions when the variable is set
  • You can prevent setting and provide only get
  • Some 'things' only work on properties (DataBinding, for example)
  • You can hide the implementation of the property [perhaps it is a ViewState variable, in ASP.NET).
Noon Silk
  • 54,084
  • 6
  • 88
  • 105
0

The point is - what if further down the line you want to make sure that every time myInt is referenced something special happens (a log file is written to, it's changed to 42 etc)? You can't do that without getters and setters. Sometimes it's wise to program for what you might need, not what you need right now.

Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
  • For some types, such scenarios are realistic. For others, they are not. Can you think of anything at all that a future version of `Point` might usefully do in a property getter or setter? If `Point` were a class with *virtual* properties, future derived classes might be able to add useful behaviors, but since particular `Point` instances have no clue about what they're being used for, and are expected to accept any `Int32` values for `X` and `Y`, I can't think of anything a future implementation could possibly add. – supercat Jun 04 '13 at 21:07
0

Actually, if you're using Silverlight, you'll realise that fields cannot be set a static resources and thus you'll have to use a property (even to access a const).

I've realised that when I tried to federate the region names I use in Composite Guidance (PRISM).

However, that's just a language limitations and apart from static/const fields I alsways use properties.

R4cOOn
  • 2,340
  • 2
  • 30
  • 41
0

The idea is you should not accidentally/unintentionally change the value of a class private field outside. When you use get and set, that means you are changing the class private field intentionally and knowingly.

rayimag
  • 893
  • 3
  • 10
  • 18
0

Setting a value into a private field only changes that field,but making them in property you can handle another arguments for example,you can call a method after setting a value

private string _email;
public string Email
{
    get
    {
        return this._email;
    }
    set
    {
        this._email = value;
        ReplaceList(); //**
    }
}




Myra
  • 3,646
  • 3
  • 38
  • 47
  • 1
    Ok but he doesn't need to do anything else than just returning the _email. And then what, what is the reason of usng property? And the reason is in m yanswer - for the future use. – agnieszka Aug 14 '09 at 12:40
-1

In simpler words, answer to your question is the access modifiers i.e. public and private.

If you use:

public int myInt;
public int MyInt 
{
     get { return myInt; }
     set { myInt = value }
}

then both MyInt property and myInt variable is available in the project to be modified. Means, if your class suppose A is inherited by class suppose B, then myInt and MyInt both are available for modification and no check can be applied. Suppose you want myInt value can be set in derive class if some particular condition pass.

This can be achieved only by making field private and property to be public. So that only property is available and conditions can be set based on that.

KamalDeep
  • 791
  • 5
  • 8