8

Is there any difference between accessing a property that has a backing field

    private int _id;
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }

versus an auto-property?

public int Id { get; set; }

The reason I'm asking is that when letting ReSharper convert a property into an auto property it seems to scan my entire solution, or at least all aspx-files.

I can't see any reason why there should be any difference between the two from outside the class. Is there?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
mflodin
  • 1,093
  • 1
  • 12
  • 22

1 Answers1

12

The compiler generates the backing field for Auto-Properties automatically, so no, there shouldn't be any difference.

ReSharper is scanning all the files, because if you have a Partial class defined, it could be using the backing field instead of the public property even though the code exists in physically different files.

For Example:

// MyClass.cs
public partial class MyClass
{
    int _id;
    public int ID { get { return _id; } set { _id = value; } }
    public MyClass(int identifier)
    {
        ID = identifier;
    }
}

// MyClass2.cs
public partial class MyClass
{
    public void ChangeID(int newID) 
    {
        _id = newID;
    }
}

ReSharper must scan all files, since it has no way to know where a partial class might be defined.

Nate
  • 30,286
  • 23
  • 113
  • 184
  • 1
    +1 makes perfect sense why the OP would say it was scanning his ASPX.CS's since they're all partial, and the code in question is very likely a page.aspx.cs where the property is defined and hence partial. – Chris Marisic Mar 04 '11 at 17:15
  • Really nice explanation, I was almost ready to ask the OP whether he was sure if ReSharper actually does that – Dyppl Mar 04 '11 at 17:22
  • Why do files in a different project need scanning, as a Partial class must be defined in the same project? Also ReSharper should be able to see from the class it's self if it is Partail as all "bits" of a partail class must be marked partail. – Ian Ringrose Mar 07 '11 at 10:49
  • @Ian -- I'm not sure about files in other solutions, but ReSharper has no way of knowing the contents of a file until after it scans it, so it must scan ALL files to find any partial classes defined. – Nate Mar 07 '11 at 20:04