Working with a hash table of unknown but similar objects (C #)

I have a hash table that can contain any number of objects. All these objects implement some similar methods / properties and some of them.

For example, all objects in a hash table may have a PrintText method that takes a single parameter of a type string. All objects, however, are created from different classes.

Is it possible for me to pull a specific object from a hash table by its key, without knowing its type before execution, and get access to all my methods and properties (and not just general ones)?

I would usually do something like

MyClass TheObject = MyHashTable [Key];

But a pullable object can be obtained from any class, so I cannot do this in this case.

+4
source share
4 answers

You can define an interface containing common methods and properties and implement this interface in all your classes. Then you can easily access these methods and properties.

But to access specific methods of an object (not contained in the interface) you need to know the type of object.

Update:

This is not clear from your question, but when you write about a hash table, I assume you mean the Hashtable class . In this case, you should take a look at the generic dictionary class (available with .NET 2.0). This class will make your code typical and save you a lot of types, for example:

IMyInterface a = new MyObject(); // with Hashtable Hashtable ht = new Hashtable(); ht.Add("key", a); IMyInterface b = (IMyInterface)ht["key"]; // with Dictionary var dic = new Dictionary<string, IMyInterface>(); dic.Add("key", a); // no cast required, value objects are of type IMyInterface : IMyInterface c = dic["key"]; 
+9
source

To solve problems with common methods and properties, you can solve by creating classes to implement the same interface. However, I do not see how you can access non-shared members. You can try using Reflection.

+1
source

dynamic in C # 4. Reflection in earlier versions.

EDIT: In some cases, defining a common interface can be both an effective and understandable way of achieving something from the nature you are describing. (β€œinspired” by the accepted answer and / or others mentioning it cannot remember the timeline)

+1
source

You can say:

 object theObject = MyHashTable[Key]; 

Then you can say:

 theObject.GetType() .GetMethod("PrintText") .Invoke(theObject, new object[] {"paramvalue"}); 
0
source

All Articles