Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

oop

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.

like image 225
Craig Bovis Avatar asked Dec 22 '22 11:12

Craig Bovis


1 Answers

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"];
like image 143
M4N Avatar answered Mar 07 '23 19:03

M4N