Search code examples
c#classlinq-to-sqlthispartial

What is difference between this.PropertyName and _PropertyName?


as I often let LinqToSql generate partial entity classes, I am wondering if my practice of adding additional properties via code is correct and if there is a better way of doing the same thing? I am also wondering what is the difference between accessing the values of other properties using this.PROPERTY_NAME vs _PROPERTY_NAME? In my web app I keep using this.PROPERTY_NAME, but I am wondering if that is, as I already said in opening sentence, the proper approach I should be using. Also, What is _PROPERTY_NAME and when do we use it?

Example:

public partial class User
{
    public bool IsThisProper {
        get{
            return this.SomeIntProperty == 10; // I usually use this
        }  
    }

    public bool WhenToUseThisApproach {
        get{
            return _SomeIntProperty == 10; // What is this in comparison to above?
        }  
    }
}

Solution

  • One is the property, and the other is the private backing field in which that property stores it's value. If you want to execute whatever code the property has in it's getter/setter, then use the property, if you don't, then don't. Chances are you want to use the property, not the field, especially with setting (setting it triggers the property changed event, so about the only time to use the property is if you don't want that event raised).