Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto implemented properties in C#

Tags:

c#

.net

Is there a way to continue to utilise auto-implemented properties while still raising a change event, such as INotifyPropertyChanged, when Set is called?

Instead of:

private string _value;
public string Value
{
  get 
  { 
    return this._value;
  }
  set
  {
    this._value = value;
    this.ValueChanged(this,EventArgs.Empty);
  }
}

Can I just do:

public string Value 
{ 
   get; 
   set 
   { 
     this.ValueChanged(this,EventArgs.Empty); 
   }
}

Although the setter looks wrong, is it possible to do this without filling my class with backing-store variables?

UPDATE: Looks like there is no standard solution to my lazy objective, I think that the best solution is to use CodeRush or Resharper to generate all my backing stores for me.

like image 840
benPearce Avatar asked Sep 15 '09 05:09

benPearce


People also ask

What are auto-implemented properties?

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.

What is the point of auto-implemented property in C#?

Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects.

What is auto-implemented object?

Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.

What is Auto property Initializers?

Auto-property initializers are basically a shortcut to setting the property value in the constructor. I wasn't overly excited about the new feature at first, but I think it makes the intention a lot more clear when you see the initial value on the same line as the auto-implemented property.


1 Answers

You can't do this. The specification for automatically implemented properties is pretty clear:

Automatically implemented (auto-implemented) properties automate this pattern. More specifically, non-abstract property declarations are allowed to have semicolon accessor bodies. Both accessors must be present and both must have semicolon bodies, but they can have different accessibility modifiers. When a property is specified like this, a backing field will automatically be generated for the property, and the accessors will be implemented to read from and write to that backing field. The name of the backing field is compiler generated and inaccessible to the user.

In other words, they can only have "get;" and "set;", with the possibility of access modifiers.

like image 122
womp Avatar answered Sep 22 '22 13:09

womp