tags:

views:

242

answers:

4

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

For example all objects in the hashtable may have a method called PrintText taking a single parameter of type string. All the objects are however instantiated from different classes.

Is it possible for me to pull out a particular object from the hashtable by its key without knowing its type before runtime, and access all its own methods and properties (not just the common ones)?

Normally I would do something like,

MyClass TheObject = MyHashTable[Key];

But the object being pulled out could be derived from any class so I cannot do that in this instance.

+9  A: 

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

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

Update:

It's not clear from your question, but when you write about a hashtable, I assume you mean the Hashtable class. In that case, you should have a look at the generic Dictionary class (available since .NET 2.0). This class will make your code typesafe and saves you from a lot of type-casting, e.g:

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"];
M4N
Exactly what I needed, thanks Martin. I didn't realise Interfaces could be used in this way!
Craig Bovis
+1  A: 

To solve problems with common methods and properties you can solve by making your classes to implement the same interface. However, I don't see how you can access non-common members. You can try to use Reflection.

Vadim
+1  A: 

dynamic in C# 4. Reflection in earlier versions.

EDIT: In some cases, defining a common interface can be both an efficient and clear way of achieving something of the nature you describe. ('inspired' by the accepted answer and/or others mentioning it - can't remember the timeline)

Ruben Bartelink
While duck-typing will work, an interface (as per the accepted answer) would be vastly preferable. Dynamic should be seen as a last resort in most cases (with the exception of COM/DLR where it is much more useful). But +1 for mentioning it.
Marc Gravell
Yep, agree. (Also I nabbed the reference to interfaces from other responses, but didnt declare it by putting an EDIT: in front of the text (though I was open in the description of the edit!))
Ruben Bartelink
A: 

You can say:

object theObject = MyHashTable[Key];

Then you can say:

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