Why should I use a private variable in a property accessor?

16,817

Solution 1

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.

Solution 2

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++;
        }
    }
}

Solution 3

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.

Solution 4

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.

Solution 5

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 . . .

Share:
16,817
Mahesh Velaga
Author by

Mahesh Velaga

Updated on June 05, 2022

Comments

  • Mahesh Velaga
    Mahesh Velaga about 2 years

    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

    • Mahesh Velaga
      Mahesh Velaga over 14 years
      sorry I was just copying from my first snippet .. forgot to delete in the second one .. thanks :)
    • Cheeso
      Cheeso over 14 years
      it's ok to ask noob questions.
    • Mahesh Velaga
      Mahesh Velaga over 14 years
      thanks, I am new to software development, but I want to learn :)
  • Chris
    Chris over 14 years
    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?
  • DOK
    DOK over 14 years
    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.
  • helium
    helium over 14 years
    No, you can use .Net 2.0 as target. But you need a C# 3 compiler.
  • Camilo Martin
    Camilo Martin over 12 years
    One good thing in case you're not sure you'll need to use additional logic, is that if you use the shorthand you can always increment it later and external code won't notice it was once just a glorified variable.