1

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.

Protector one
  • 6,926
  • 5
  • 62
  • 86

4 Answers4

2

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

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
  • 49,681
  • 17
  • 108
  • 138
0

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.

user224564
  • 1,313
  • 1
  • 10
  • 14
0

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
  • 560
  • 3
  • 11