Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 809
ashley Avatar asked Jul 24 '13 04:07

ashley


People also ask

WHAT IS &N in C?

*&n is equivalent to n . Thus the value of n is printed out. The value of n is the address of the variable p that is a pointer to int .

Which is more difficult C or C++?

Or Which is better C or C++? Answers: Actually, both are difficult and both are easy. C++ is built upon C and thus supports all features of C and also, it has object-oriented programming features. When it comes to learning, size-wise C is smaller with few concepts to learn while C++ is vast.

How do I code C in Visual Studio?

Download & Install the C/C++ Extension 1. We need to click on the extension button that displays a sidebar for downloading and installing the C/C++ extension in the visual studio code. In the sidebar, type C Extension. In this image, click on the Install button to install the C/C++ extension.


2 Answers

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.

like image 107
Claies Avatar answered Oct 04 '22 22:10

Claies


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.

like image 43
Maximum Cookie Avatar answered Oct 04 '22 20:10

Maximum Cookie