Verkade89
Verkade89

Reputation: 393

Setting dictionary key and value types with variables

I am currently struggling to create a dictionary. I want to create it so that it can be used in multiple situations. However, these situations vary from key and value types. So while you normally do:

Dictionary<int, string> Something = new Dictionary<int, string>();

I want to do something like:

Dictionary<variable1, variable2> ..............

Doesn't matter much what variable1 is. It can be a string, that stores 'string', or 'int' as value. I could also use variable1.getType() to determine the type. Either way would work for me. But the way I did above, well, that is just incorrect. There must be another way to set the key and value type based on variables... right?

Something just shoot into my head, to use if's to check what the type is, and based on the type make the dictionary use that type. But with the amount of types, it's going to be a lot of if's, and I feel like there has to be a better way.

Searching hasn't helped me much. Well I learned some other things, but no solution to my problem. In every single case, dictionary TKey and TValue has been set manually. While I want to set them, with a variable that I take from some source.

Upvotes: 1

Views: 5215

Answers (3)

Dzienny
Dzienny

Reputation: 3417

There must be another way to set the key and value type based on variables... right?

Yes, there is. You can make a helper method that creates a dictionary, example:

public static Dictionary<K, V> CreateDictionaryFor<K, V>(K key, V value)
{
    return new Dictionary<K, V>();
}

Then, you can use it with variable1 and variable2:

var dictionary = CreateDictionaryFor(variable1, variable2);

Upvotes: 5

Philip W
Philip W

Reputation: 791

A pssibility would be to capsulate the dictionary in a new class, and create the dictionary via a generic method:

public class GenericDictionary
{
    private IDictionary m_dictionary;

    public bool Add<TA, TB>(TA key, TB value)
    {
        try
        {
            if (m_dictionary == null)
            {
                m_dictionary = new Dictionary<TA, TB>();
            }

            //check types before adding, instead of using try/catch
            m_dictionary.Add(key, value);

            return true;
        }
        catch (Exception)
        {
            //wrong types were added to an existing dictionary
            return false;
        }
    }
}

Of course the code above needs some improvements (no exception when adding wrong types, additional methods implementing the dictionary methods you need), but the idea should be clear.

Upvotes: 1

scartag
scartag

Reputation: 17680

You can try doing Dictionary<object, object>.

That way you can pass whatever you need to pass and check the type as needed.

var dict = new Dictionary<object, object>();

dict.Add(45, "dkd");

Upvotes: 2

Related Questions