Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do i cast an object to dictionary?

The dictionary key & value can be any type.

What I have tried:

C#
public class Example {

    void CallMethod () {
        SomeMethod (new Dictionary<string, bool> ());
        SomeMethod (new Dictionary<int, long> ());
        SomeMethod<Dictionary<string, bool>> (new Dictionary<string, bool> ());
    }
    
    void SomeMethod (object value) {
        var dic = value as Dictionary<,>;
        // What is type of Dictionary key or value?
    }

    void SomeMethd<T> (T value) {
        // T can be Dictionary, int, bool, List, ...
        if (value is Dictionary) {
            // T is dictionary, but we don't know type of key and value
            // How do i cast it to dictionary?
            var dic = value as Dictionary<,>;
            foreach (var item in dic) {
                
            }
        }
    }

    T SomeMethod<T> () {
        // I want to load the dictionary here
        if (typeof(T) is IDictionary) {
            // Now, what is type of the key and value?
            IDictionary dic = new Dictionary<,> ();
            int count = 1;
            for (int i = 0; i < count; i++) {
                dic.Add (SomeMethod<Type of Key> (), SomeMethod<Type of value> ());
            }
            // Throws an exception
            return dic;
        }
        return default(T);
    }
    
}
Posted
Updated 2-Mar-23 22:37pm
v3
Comments
Mehdi Gholam 22-Jul-17 6:08am    
What do you intend to do in SomeMethod() ?
EmpireWorld 22-Jul-17 6:12am    
I want to write the object using BinaryWriter.

Unless you know the type of the dictionary - and that means key and value - the only way to do it is to cast it to a Dictionary<object, object> - which is a very bad idea as it gets rid of the strong typing which makes C# so robust. At this point you are relying on runtime-casts to use the dictionary you create, and that's a poor idea.

Have you instead considered using Generics, so you don't have to cast your Dictionary, the types are inferred when you call the method?
void SomeMethod<K, V>(Dictionary<K, V> dict)
    {
    ///...
    }
It'll make your code both more robust, and a lot easier to read.
 
Share this answer
 
Comments
EmpireWorld 22-Jul-17 6:27am    
I need a method that takes only one generic type and one argument, that accepts Primitive Types, Generic Types such as Collections, List, Dictionary and Custom classes. So how do i do it while you say to make overload for dictionary?
OriginalGriff 22-Jul-17 6:49am    
Because the properties and methods available are different, I'd produce overloads that take generics:
void SomeMethod<K, V>(Dictionary<K, V> dict)
{
///...
}
void SomeMethod<t>(List<t> list)
{
}
void SomeMethod<t>(IEnumerable<t> enumerable)
{
}
You can add other parameters to those as required.
EmpireWorld 22-Jul-17 7:01am    
Please check the T SomeMethod<t> (); in the question, i need a recursive method.
OriginalGriff 22-Jul-17 7:09am    
Don't: create a method which accepts a generic dictionary<K, V> and K is the type of the key, and V is the type of the Value. You can use those inside the method to create new instances, or whatever you need.

What are you trying to achieve? You seem to be overcomplicating things here.
EmpireWorld 22-Jul-17 7:12am    
I am trying to make a Save and Load solution.

I want to be able to save everything such as Dictionaries, Custom Classes, ...

What i have is a single Save and Load method.

Save<t> (T value);

and

Load<t> ();

I need a recursive save and load functionally for both.

How do i achieve this?
Depending on how much the type information is important to you within the SomeMethod() method you can do:
C#
// minimal type info needed
void SomeMethod (System.Collections.IDictionary dictionary)
{
   foreach(var k in dictionary.Keys)
   {
      // k and dictionary[k] as value
   }
}

Or if the types are needed:
C#
// overloaded for each case
void SomeMethod (System.Collections.Generic.Dictionary<int,long> dictionary)
{
   foreach(var kv in dictionary)
   {
      //access to kv.Key and kv.Value as int and long
   }
}

void SomeMethod (System.Collections.Generic.Dictionary<string,bool> dictionary)
{
   foreach(var kv in dictionary)
   {
      //access to kv.Key and kv.Value as string and bool
   }
}
 
Share this answer
 
v2
Comments
EmpireWorld 22-Jul-17 6:30am    
I need a method that takes only one generic type and one argument, that accepts Primitive Types, Generic Types such as Collections, List, Dictionary and Custom classes.
Also i don't have access to kv.Key or kv.Value. (please try your script)
Mehdi Gholam 22-Jul-17 6:35am    
Sorry, fixed.
EmpireWorld 22-Jul-17 6:38am    
What is the type of k? is it object?

As i checked it is object.

Nice, Thanks, it works as well.

Your first example is the solution.

i tried it:

        void Method ( object value )	{		IDictionary dic = value as IDictionary;		foreach ( var item in dic.Keys )		{			Debug.Log ( item );			Debug.Log ( dic [ item ] );		}	}


But there is no need to use IDictionary type as argument just replace it with object. and i will accept your solution.
Mehdi Gholam 22-Jul-17 6:40am    
Yes
EmpireWorld 22-Jul-17 6:46am    
Your first example is the solution. please update it and make it like my question. i will accept your question.
Hope, i got the question correctly. Object to Dictonary. It runs without error.

var dic = value as Dictionary<object,object>;
 
Share this answer
 
Comments
EmpireWorld 22-Jul-17 6:13am    
How do i get the dictionary key type? in your code the type of the key and value both are object there is no difference?!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900