1

Possible Duplicate:
Difference between Property and Field in C# .NET 3.5+
Why should I use an automatically implemented property instead of a field?

Both Examples below do exactly the same, have identical access writes within and outside of the class... So why does everyone seem to use Example 1 as apposed to Example 2? I'm sure I'm just missing something, but this has been bugging me for a while now and I haven't been able to find a clear cut answer.

class SampleClass
{
    /// Example 1
    /// Shown by online examples. 
    /// Why use a Field AND a Property where you could just use Example 2?
    private int age;
    public int Age { get { return age; } }
    private void setAge()
    {
        age = 1;
    }

    /// Example 2
    /// Tidier code and better understanding of how Age2 can be accessed. 
    /// Personally I prefer this method, though am I right to use it over Example 1?
    public int Age2 { get; private set; }
    private void setAge2()
    {
        Age2 = 1;
    }
}
Community
  • 1
  • 1
Robula
  • 649
  • 1
  • 12
  • 29
  • 2
    Neither of those duplicates are valid. He's not asking if he should use a field vs a property, he's asking about manually implemented properties vs auto implemented properties. – Servy Nov 27 '12 at 19:32
  • 1
    @OP also note that auto implemented properties were introduced in C# 3.0, but properties have been in the language since C# 1.0. Many examples of manually defined properties are either older code samples that have stuck around, or from people who hadn't (or haven't) yet gotten used to the newer syntax. Of course there are also cases where you can do stuff manually that the auto props can't, but that's not true of the example you've posted. – Servy Nov 27 '12 at 19:34
  • This is probably where I struggle most, what's new and what is better practice? If Example 2 wasn't possible in earlier .NET versions and that Example 1 was necessary to achieve the same effect. It's reassuring to know that by using Example 2 I am using more modern syntax and not unnecessarily bloating my code with Example 1. :) – Robula Nov 27 '12 at 20:04

3 Answers3

1

You will have to use a backing field if you want to provide any actual functionality on the property setter or getter. For example, if you want to have validation on your setter, you will need to use a backing field.

public class MyClass
{
    private string myString = "blah";

    public string MyNotNullString
    {
        get
        {
            return this.myString;
        }
        set
        {
            if (value == null)
            {
                throw new ArgumentNullException("Cannot set MyNotNullString to null");
            }
            this.myString = value;
        }
    }
}
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
0

I would use Example2 if possible every time for the tidiness factor... unless there was a situation where I needed a field, as in @Platinum Azure answer.

The only other benefit I can think of for Example1 is that you can set a breakpoint in the getter or setter methods, as a quick way of finding out who's changing the value.

demoncodemonkey
  • 11,730
  • 10
  • 61
  • 103
  • Hmm okay. With all of this in mind, the way I understand it is Fields are ideal for variables/objects within the stating class. Whereas Properties have an immediate advantage where I need to safely expose variables/objects outside of the stating class with appropriate read/write access modifiers. Am I on the right wave length here? :) – Robula Nov 27 '12 at 19:58
  • Oh I didn't realise this was a Field vs Property question, I assumed you were comparing an auto-property with {get;set;} vs a property-with-backing-field. Well, ideally, fields should be private, and for properties use auto-props if possible... that's my take on it anyway. – demoncodemonkey Nov 27 '12 at 20:08
  • It wasn't... I'm just a beginner trying to grasp an understanding of how I should go about doing something wether that includes the use of fields or not. Before asking this I had never heard of an "auto" property. Still not sure why I would need a backing field, but maybe I'll realise just what the requirement is when my skills improve and the need arises. For now I believe I have my answer, thank you all :) – Robula Nov 27 '12 at 20:13
0

If I am using VS2008 or greater and don't need it compilable in VS2005, in general I use the shorthand or:

public string SomeProperty { get; set; }

But sometimes you need a backing field, especially when you are implementing INotifyPropertyChanged.

private string _someProperty;
public string SomeProperty
{
    get { return _someProperty; }
    set
    {
        _someProperty = value;
        OnPropertyChanged("SomeProperty");
    }
}

But even if I do have a backing field, I still set the value through the Property, for consistency.

taylorjonl
  • 869
  • 9
  • 15
  • Thanks. This is not something I have done, or even thought of. I assume INotifyPropertyChanged is an interface that triggers an event when the property is changed? Please excuse me for my inexperience... – Robula Nov 27 '12 at 20:09
  • Correct, it is used heavily when working in WPF with the MVVM pattern. Basically with this pattern you create a ViewModel class and the View binds to properties on the ViewModel. The View registers for the PropertyChanged event, so when the value in the ViewModel changes the View can update the appropriate controls with the new data. – taylorjonl Nov 27 '12 at 20:11