tags:

views:

78

answers:

4

I have instances of class A and B, and both classes implement a member 'Text'. Is there a way to access member Text in a generic way? I'm hoping for something analogous to the javascript way of simply saying:

instance['Text'] = value;

Note: these two classes unfortunately do not both implement the same interface with a Text member.

+2  A: 

Unlike javascript, C# is a static language and if both classes don't implement a common interface or base class you could use reflection to achieve the same goal.

instance.GetType().GetProperty("Text").SetValue(instance, "new value", null);
Darin Dimitrov
Excellent! Exactly what I was looking for.
Protector one
+1  A: 

If you can't make A and B implement the same interface, then you need to use reflection to access any class member by name, something like this:

typeof(A).GetProperty("Text").GetValue(theInstance, null);

where theInstance would be an instance of the A class.

Konamiman
Thanks for naming the technique! You almost had best answer. ;)
Protector one
A: 

Ideally you should have single class with member "Text" which will be base for A and B. Probably it is not convinient, but it is more reliably and correct. Try not to use reflection where you can do the same in other way.

A: 

If you can make A and B implement the same interface

 interface ISomeGenericNameForAAndB
{
    string Text { get; }
}
class A :ISomeGenericNameForAAndB
{
    public string Text { get { return "some Text from A"; } }    
}
class B : ISomeGenericNameForAAndB
{
    public string Text { get { return "some Text from B"; } }
}

ISomeGenericNameForAAndB anAInstance = new A();
ISomeGenericNameForAAndB aBInstance = new B();
irfn