Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to intercept setters and getters in C#?

In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

public class Person {     public string FirstName { get; set; }     public string LastName { get; set; } } 

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?


Edit: I want to do this without defining a backing field.

like image 818
Edgar Gonzalez Avatar asked May 17 '11 12:05

Edgar Gonzalez


Video Answer


2 Answers

Not generally; a few options though;

  • inherit from ContextBoundObject - which does allow this, but at a performance cost
  • write an explicit property (i.e. with a backing field), and add a utility method call manually
  • look at compile-time weavers, such as PostSharp - generally by spotting an attribute or similar
  • look at runtime code generators, as offered by some DI/IoC tools (and some other "decorator" based tools) - which either decorate or subclass your object to add the extra code
like image 83
Marc Gravell Avatar answered Sep 22 '22 13:09

Marc Gravell


It is possible to do directly in the property body itself, but then you need to use a proper backing field instead of auto-implemented properties.

private string firstName;  public string FirstName  {    get { return firstName;}    set    {     if(check(value))     {        firstName = value;     }   }  } 

Even with auto-implemented properties you get a backing field - this is generated by the compiler and you don't have direct access to it.


Edit:

Seeing as you don't want a backing field, you have other options - using an AOP tool such as PostSharp could help with that.

like image 30
Oded Avatar answered Sep 19 '22 13:09

Oded