Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving state in an extension method

The C# team has previously considered adding extension properties, events, etc. to C#.

Per Eric Lippert:

http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx

For these features to be useful however, they would have to be able to store some new kind of state with an object. It seems like the only way to do this would be to use a dictionary and associate each instance of an object with whatever the additional state is.

It would be useful if it were possible to copy this functionality "manually" by creating my own dictionary (and perhaps get/set extension methods). However, in order to associate a particular instance of an object with some state you would need to hash the actual reference to the object. In another language you might do this by hashing its memory location, however in C# that is not guaranteed to stay constant, and using unsafe code to accomplish this feature is far from ideal anyway.

Does anyone know if it's possible to get some hashable reference to an object that does not change as the object's internal state changes? There obviously is some internal mechanism to keep track of individual objects regardless of their memory location, but I'm not sure if that is exposed to user code.

Note: Simply hashing the object itself will not work at all, because GetHashCode() depends on an object's internal state not on which object it is.

Thanks for any insight.

like image 495
MgSam Avatar asked May 18 '12 14:05

MgSam


People also ask

What does extension method mean?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is extension method with example?

An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.

What is an advantage of using extension methods?

Extension methods can also help keep your classes and class dependencies clean. For instance, you may need a Bar() method for the Foo class everywhere Foo is used.

Are extension methods good practice?

Adding extension methods to any type is a great way to improve productivity and simplify code. You should do this wherever it feels beneficial to you, without worrying about any of these details.


1 Answers

You're looking for the ConditionalWeakTable class.

like image 158
SLaks Avatar answered Sep 19 '22 23:09

SLaks