views:

463

answers:

8

Hi all,

Sorry If I am being noob, I have this doubt, why do we use private variables and set them using properties ?

Why can't we just use properites alone ?

I am talking about situations like this

private string _testVariable;

public string MyProperty
{
    get { return _testVariable;}
    set {_testVariable = value;}
}

I am thinking of simply using

public string MyProperty { get; set; }

Why redundant private variable? are these two strategies different ? can anyone please throw some light on this.

Thanks

+1  A: 

The second example that you give:

public string MyProperty { get; set; }

Is only available in later versions of the .Net framework (v3.0 onwards I believe)

The first example allows you to set breakpoints on the return and assignment statements, causing your debugger to break when the property is assigned / read.

Kragen
No, you can use .Net 2.0 as target. But you need a C# 3 compiler.
helium
+2  A: 

The 1st code snip allws you to modify some private class state. Wrapping private state in a property is nice because it hides the implementation. Later you can change the implementation and the property (external interface) may remain unchanged.

For example, suppose instead of setting a single string within the setter, you set the string in a private store of some sort. You write it to a file, or write it to shared memory. Or maybe you compute the hash of the string only, and don't store it at all, as you might do with a password.

The auto properties in your 2nd code snip are not related to the private variable at all. The auto-property design, like the explicit property design used in the first snip, allows future modification. As part of that modification, for example, you could convert from auto properties to explicitly implemented properties.

Cheeso
+11  A: 

Your examples are semantically the same. The concise property declaration syntax (just having { get; set; }) is a shortcut available in C# 3.0. The compiler actually creates a private backing variable and a simple getter and setter as in your first example.

If all you're doing is creating a getter and setter (and nothing actually happens when either occurs), then the concise syntax is a good option. If you have to perform any other actions (redraw a control, for example) when you set the value, then the full syntax is required.

Adam Robinson
A: 

Property is basically the wrapper around a field. This wrapper enables to use the variable from outside world. In C#3.0 you can simply declare a property like public string MyProperty { get; set; } The compiler declares a private variable automatically and get set methods for that also. If you need to perform any calculation inside the class that is declaring the property, then you should use the private field for that.

viky
A: 

Sometimes you don't know when you first write the code whether you may be adding some more code later that needs to use the private variable. Sure, you can add it later if needed. I just automatically create the private variable, assuming that it will be used later.

This may be more relevant in large enterprise apps or rapidly evolving apps (agile) where the full implementation may not be known during the initial coding.

DOK
Changing from an automatic property to one backed by an explicit private variable is fairly easy and non-breaking. I don't see why you'd want to clutter your code needlessly on the off chance that someone may need it later. Do you do this with other parts of your code too?
Chris
Nope, just properties. Always creating the private variables gives me a predictable code state. And it's easier to do this if you use a code generator to create all the properties :) But your point is well taken.
DOK
+4  A: 

Why redundant private variable? are these two strategies different ? can anyone please throw some light on this.

If all your doing is reading/writing a variable, then no. Otherwise, there's two reasons why you'd want a private variable:

Data validation

// Data validation
public class IntWrapper
{
    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            if (value < 0) { throw new Exception("Value must be >= 0"); }
            _value = value;
        }
    }
}

Getter/setter wraps up an underlying data store

public class StringBuffer
{
    List<char> chars = new List<char>();

    // Wraps up an underlying data store
    public string Value
    {
        get { return new String(chars.ToArray()); }
        set { chars = new List<char>(value.ToCharArray()); }
    }

    public void Write(string s) { Write(chars.Count, s); }

    public void Write(int index, string s)
    {
        if (index > chars.Count) { throw new Exception("Out of Range"); }
        foreach(char c in s)
        {
            if (index < chars.Count) { chars[index] = c; }
            else { chars.Add(c); }
            index++;
        }
    }
}
Juliet
+1  A: 

Mashesh, We all had to start somewhere! You asked about private vars vs properties with this ex:

private string _testVariable;

public string MyProperty
{
    get { return _testVariable;}
    set {_testVariable = value;}
}

-or-

public string MyProperty { get; set; }

Did you consider:

public string MyProperty { get; private set; }

You can apply scope to property getters/setters . . . . cool stuff. Oh yeah . . . when using this type of property within the defining class (like in a constructor) prepend it with a 'this.' - so an assignment would look like 'this.MyProperty = "An Assigned String";'. This makes your intentions much more clear . . .

TheEruditeTroglodyte
A: 

This isnt related to C# the langugage, but more the application.

One reason to use properties, is that its treated as "Special" in many frameworks. For example, Silverlight and WPF will bind to properties and not to fields

mrwaim