views:

66

answers:

3

I am using a class with a string property on it. I am looking for some sort of event notification when somebody reads the value of this property, so that I can provide the property dynamically. For example, usually somebody would do:

string foo = someClass.Property;

And it returns whatever string value is currently assigned to Property.

However, I want to say something like:

someClass.PropertyRead += new EventHandler<PropertyReadEventArgs>("Property", Property_Read);

private void Property_Read(object sender, PropertyReadEventArgs e)
{
    e.Value = "some dynamically generated string here.";
}

Any idea if something like this is possible?

+2  A: 

Why not use plain property getter?

public string Property {
    get { return Generate(); }
}

If you'd rather inject the strategy you can do:

public Func<string> PropertyGetter{ get; set; }

public string Property{ 
   get{
       return PropertyGetter();
      }
}

And then

myclass.PropertyGetter = Console.ReadLine;
+1  A: 

If you are using a Property then you are probably using a getter in which you can create your dynamic string.

public String SomeProperty
{

get
 {
    return DynamicString();
 }

}

private String DynamicString()
{
   return "some dynamically generated string here.";
}
Stan R.
A: 

It sounds like you want to add properties at runtime, and do so without using a special syntax to access them.

So myClass.Property does not exist at compile time.

My (guess) is you would need to create a dynamic proxy for your object so you can intercept the calls and provide implementations for missing properties.

I'm not sure about .NET 4.0 and whether it makes this easier or not.

sylvanaar
"I'm not sure about .NET 4.0 and whether it makes this easier or not." : it does (see the ExpandoObject, for instance). But that's not the point of the question ;)
Thomas Levesque
I was thinking it did - but didn't have time to check my facts.
sylvanaar