Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

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.

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.

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top