Reputation: 7271
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.
Upvotes: 1
Views: 157
Reputation: 560
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();
Upvotes: 0
Reputation: 1039238
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);
Upvotes: 2
Reputation: 1323
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.
Upvotes: 0
Reputation: 50313
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.
Upvotes: 1