views:

122

answers:

6

I've created this "question" as a community-wiki, because there is no right or wrong answer. I only would like to know how the community feels about this specific issue.

When you have a class with instance variables, and you also created properties that are simply getters and setters for these instance variables, should you use the properties inside your own class, or should you always use the instance variable?

Having auto-properties in C# 3.0 made this an even harder decision.

Using properties:

public class MyClass
{
    private string _name;

    // could be an auto-property of-course
    public string Name { get { return _name; } set { _name = value; } }

    public void Action()
    {
        string localVar = Name;
        // ...
        Name = "someValue";
        // ...
    }
}

Using instance variables:

public class MyClass
{
    private string _name;

    public string Name { get { return _name; } set { _name = value; } }

    public void Action()
    {
        string localVar = _name;
        // ...
        _name = "someValue";
        // ...
    }
}

(for those who hate member prefixes, I apologize)

Personally, I always use the latter (instance variables), because I feel that properties should only be used by other classes, not yourself. That's why I mostly stay away from auto-properties as well.

Of course, things change when the property setter (or getter) does a little more than just wrapping the instance variable.

Are there compelling reasons to pick one or the other?

+1  A: 

I always use instance variables as well. The reason is because properties might be doing stuff like validating arguments (like in a setter) for not null or not empty. If you're using the variable inside your class code, there's no need to go through the extra overhead of those checks (assuming you know the variable value is valid). The properties could be doing other things as well (logging, for example), that are important for the public API, but not for internal usage, so again, it's better to avoid the overhead and just use the instance variable in my opinion.

dcp
-1 Most of the time, you would need that kind of business logic for calls inside the class as well. So, basically, you would actively choose NOT to use the property for a good reason. e.g. if you know when it would be best not to. Otherwise there's no overhead involved whatsoever, because in a non-debug screnario, simple property setter/getter are inlined anyways.
Robert Giesecke
@Robert Giesecke -1 to your comment. Validating arguments for not null and not empty takes extra overhead. There's no point in doing that if it's not necessary, because it IS extra overhead (please re-read my original response). You're not even taking into account that property setters might need to be thread safe (i.e. use a lock block), in which case you wouldn't want to call the property if you were in the constructor and initializing the variable value, for example. So again, there are other types of overhead you don't seem to be considering.
dcp
A: 

I don't like prefixing members either, but actually I find I can write something like this accidently and not spot it until run time. Which kinda tempts me to avoid using properties where they're not necessary... but I still do, currently!

Public String MyString
{
   { get { return this.MyString; } }  //<== Stack Overflow
   { set { this.myString = value; } } 

}
private String myString;
Ian
A: 

I think that there is no difference between these two approaches.

Auto-implemented properties is just a quick way to access private members which are created any way.

Example from MSDN:

class Customer
{
    // Auto-Impl Properties for trivial get and set
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

    // Constructor
    public Customer(double purchases, string name, int ID)
    {
        TotalPurchases = purchases;
        Name = name;
        CustomerID = ID;
    }
    // Methods
    public string GetContactInfo() {return "ContactInfo";}
    public string GetTransactionHistory() {return "History";}

    // .. Additional methods, events, etc.
}
sashaeve
A: 

Hi there.

99% of the time I use the property rather then the instance variable. In the past, I've worked with a lot of code that used the instance variable and when there was a bug associated with that variable, I had to put a breakpoint on every line of code that referenced it.

I decided to use properties instead, either public or private, to wrap around the instance variable. Doing this means that I only have to put a breakpoint in the getter/setter of the property if I need to debug an issue with the instance variable, rather then having (potentially) a lot of breakpoints scattered all over the code.

Cheers. Jas.

Jason Evans
+1  A: 

I think it becomes more difficult to change the internal implementation if the code uses its own public interface.

Difficult to explain but consider these expressions:

mTotalPrice = mPrice * mQuantity;

mTotalPrice = Price * Quantity;

What to do in the second expression if I need to change the internals to express all prices in € instead of $ (without affecting the public interface which still uses $)?

One solution is to make the expression more complex by adding the opposite of the change in the property.

mTotalPrice = Price / Rate * Quantity

The other solution is to start to use the private field instead.

mTotalPrice = mPrice * Quantity

In the end you get a mix of private and public use. The only way to get consistent use is to always use the private field.

adrianm
+2  A: 

This is a fairly frequently asked question. Here's my article that describes some of the issues:

http://blogs.msdn.com/ericlippert/archive/2009/01/14/automatic-vs-explicit-properties.aspx

Eric Lippert