Add code to C# get/set of property without needing backing field?

13,361

Solution 1

Simple answer is no, you can't have it both ways. From .NET Docs:

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.

Solution 2

There are not any solutions for this built into the framework, and you cannot modify existing types via reflection (in order to add the logic at runtime). The only way to accomplish this seems to be at compile time.

There is a product http://www.postsharp.net/ that can accomplish this (intercept property/method calls), and there does appear to be a free edition.

Share:
13,361
ashley
Author by

ashley

Updated on June 05, 2022

Comments

  • ashley
    ashley almost 2 years

    You know how you can have a property that automatically generates a backing field? Like if I go:

    public String SomeProperty {get; set;}
    

    I know that if I want to add code to that property I have to create the backing field as so:

     public string someProperty = string.Empty;
     public string SomeProperty
     {
         get { return someProperty; }
         set
         {
             someProperty = value;
             DoSomething();
         }
     }
    

    Basically, what I want to know is... is there any way to do this but without having to create the backing field? For example I could use it to trigger some kind of event that occurs when a property is set. I'm looking for something like this:

     public string SomeProperty
     {
         get;
         set { this.OnSomeEvent; }
     }
    

    But I know that'll cause a compile error because get needs do declare a body if set does.

    I've researched and I cant find anything, but I thought I'd check to see if anyone knew.

    I guess what I'm really after is some way to trigger an event when a property is changed but without having to add all that extra clutter. Any suggestions?

  • Claies
    Claies almost 11 years
    postsharp is a great alternative, which allows you to do aspect oriented programming (AOP). AOP isn't as much about reducing clutter as it is about managing Cross Cutting Concerns (behaviors that are used across a large number of business requirements, and cannot easily be isolated)