Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# properties with repeated code

I have a class with a bunch of properties that look like this:

public string Name
{
    get { return _name; }
    set { IsDirty = true; _name = value; }
}

It would be a lot easier if I could rely on C# 3.0 to generate the backing store for these, but is there any way to factor out the IsDirty=true; so that I can write my properties something like this and still get the same behaviour:

[MakesDirty]
public string Name { get; set; }
like image 764
Craig.Nicol Avatar asked Sep 15 '08 14:09

Craig.Nicol


2 Answers

No. Not without writing considerably more (arcane?) code than the original version (You'd have to use reflection to check for the attribute on the property and what not.. did I mention it being 'slower').. This is the kind of duplication I can live with.

MS has the same need for raising events when a property is changed. INotifyPropertyChanged that is a vital interface for change notifications. Every implementation I've seen yet does

set
{ 
  _name = value; 
  NotifyPropertyChanged("Name"); 
}

If it was possible, I'd figure those smart guys at MS would already have something like that in place..

like image 142
Gishu Avatar answered Nov 15 '22 11:11

Gishu


You could try setting up a code snippet to make it easy to create those.

like image 39
Joel Coehoorn Avatar answered Nov 15 '22 12:11

Joel Coehoorn