Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# property setter body without declaring a class-level property variable

Tags:

c#

properties

Do I need to declare a class-level variable to hold a property, or can I just refer to self.{propertyname} in the getter/setter?

In other words, can I do this? (where I haven't defined mongoFormId anywhere):

public string mongoFormId 
{
    get
    {
        return this.mongoFormId;
    }
    set
    {
        this.mongoFormId = value;
        revalidateTransformation();
    }
}
like image 766
whatdoesitallmean Avatar asked Jun 21 '13 15:06

whatdoesitallmean


1 Answers

You can either use automatic accessors or implement your own. If you use automatic accessors, the C# compiler will generate a backing field for you, but if you implement your own you must manually provide a backing field (or handle the value some other way).

private string _mongoFormId;

public string mongoFormId 
{
    get { return this._mongoFormId; }
    set 
    {
        this._mongoFormId = value;
        revalidateTransformation();
    }
}

UPDATE: Since this question was asked, C# 6.0 has been released. However, even with the new syntax options, there is still no way to provide a custom setter body without the need to explicitly declare a backing field.

like image 154
p.s.w.g Avatar answered Oct 27 '22 07:10

p.s.w.g