Thomas Clayson
Thomas Clayson

Reputation: 29925

Creating a dictionary of any object

What I want is the ability to store name,object pairs.

Unlike objC c#'s Dictionary requires types. In objC I would use id to mean "any object".

How would I manage this in c#.

So what I'm looking for is:

Dictionary<String,id>.

Sorry if this is really basic!

Upvotes: 2

Views: 798

Answers (4)

Aleksei
Aleksei

Reputation: 307

Not sure if I understood you correctly but you can make the following:


    Dictionary s = new Dictionary();
    Object a = new Int32();
    a = 1;
    Object b = new Double();
    b = 2.0;
    s.Add("a", a);
    s.Add("b", b);
    Int32 v = Convert.ToInt32(s["a"]);
    Double u = Convert.ToDouble(s["b"]);
    Console.WriteLine(v + " " + u);

Upvotes: 0

František Žiačik
František Žiačik

Reputation: 7612

Asking this may indicate there could be some bad design hidden behind this. It always does when you need a collection of heterogenous objects.

Because of not knowing the type of objects you have in the collection, you always need to do some kind of type checking, such as if (dictionary["xy"] is string) {...} which is a code smell.

Would some kind of wrapping into a common class be an option? That would allow you to specify some common operations on it (because you probably need some common operations if you need it to be in the same dict). For example something like (consider it as pseudocode):

class Base
{
   bool IsCollection;
}

class StringItem : Base
{
   string Contents;
   IsCollection = false;
   override ToString() { return this.Contents; }
}

class ListItem : Base
{
   List<StringItem> Contents;
   IsCollection = true;
   override ToString() { return string.Join(",", this.Contents.ToArray() }
}

Then you could have a Dictionary<string, Base> and use operations defined on Base such as ToString or any custom.

Upvotes: -1

Adam Houldsworth
Adam Houldsworth

Reputation: 64467

Without going into a lot of faffery to talk to multiple strongly typed lists of objects, the simplest way to achieve this is with a Dictionary<string, object> and to cast out your object type as you need it:

int i = (int)myDictionary["Age"];
string n = (string)myDictionary["Name"];

There are a few dynamic options here such as ExpandoObject:

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx

If you go the object dictionary approach, pay attention to boxing on value types. Using the dynamic approach won't have the boxing implications, but will require runtime resolution, so performance again is slightly impacted.

Nothing comes for free, but by and large you shouldn't see the effects of this minor overhead.

Upvotes: 4

chemicalNova
chemicalNova

Reputation: 841

There's always the new dynamic type in .NET 4 if unboxing is an issue.

Upvotes: 0

Related Questions