Is there anyway to create a dynamically retrievable method which somehow monitors an object’s state, yet only has to be called once and will update its result once the state of the object it observes has been modified or changed in some way which wasn’t equal to the state it was at before at the time the method was called.
I have a script here to illustrate my point:
bool isNull = false;
Object obj = new Object();
isNull = (bool)obj.ExtNull();
string reply = TestMethodA(isNull);
Console.WriteLine("Is object null? Answer: {0}. State of isNull: {1}", reply, isNull);
obj = null;
Console.WriteLine("\n\nNulling object... ");
Console.WriteLine("\n\nNew answer: ");
Console.WriteLine("\n\nIs object null? Answer: {0}. State of isNull: {1}", reply, isNull);
Console.Read();
}
public static string TestMethodA(bool isNull)
{
string str;
if (isNull)
str = "yes";
else
str = "no";
return str;
}
As we can see, an object calls an extension method casted as a bool, which meets the method’s return type. This statement is then assigned to the bool isNull variable.
A string is then called, and assigned TestMethodA, which passes isNull as its argument. Once isNull is received in the method’s parameter it analyzes whether or not the boolean is true or false. If it’s true (meaning that the object is null), the string variable called within the method takes “yes” for its value. Likewise, if not, it will take “no.”
The string is then returned, and passed back to the method. Both the string and the boolean are posted in the Console.WriteLine method.
After this happens, the obj reference variable assigns itself null, losing its once had reference.
The WriteLine statement then posts the same statement it had before, analyzing the boolean and the state of the object. Of course, despite the fact that the object’s state is now null,
So, since C# doesn’t really have pointers (a real shame, really, now that I think about it) without unsafe code, is there any way to achieve this dynamically?
It’s expensive, performance wise, and it’s not completely real time, but you may be able to accomplish what you want here using Reactive Extensions.
Check out the examples here:
http://rxwiki.wikidot.com/101samples#toc1
Specifically, you’d be interested in creating an
Observable.Sampleor anObservable.Interval.Aside from that, you could go the proxy generation route…but that involves more control over the actual types you want to observe. If you are in control of the type definition, you could declare all your properties as virtual and create instances of your type using dynamic proxies (Castle Windsor/DynamicProxy is one tool to do this, though there are others). You could automatically make your type implement INotifyPropertyChanged
http://www.codewrecks.com/blog/index.php/2008/08/04/implement-inotifypropertychanged-with-castledynamicproxy/
and simply bind an event handler to watch the
PropertyChangedevent.