Reputation: 3892
I want to create a Dictionary with TKey as string and the TValue to be from type which is not know at compile time.
Let's say for example I have a function
createDict(Type type)
{
Dictionary<string, {here's the type from the func. argument}> dict = new Dictionary..
}
Is this scenario possible or I'm missing something very basic ?
Upvotes: 0
Views: 363
Reputation: 499152
Make the method generic:
public void CreateDict<T>()
{
Dictionary<string,T> dict = new Dictionary<string,T>();
}
Though you may want the return type to also be Dictionary<string,T>
and add constrains to the generic type parameter.
You would call it as:
CreateDict<MyCustomType>();
The above assumes the type can be passed in during compile time.
Upvotes: 3
Reputation: 56716
You can do with a bit of reflection:
Type dict = typeof (Dictionary<,>);
Type[] parameters = {typeof (string), type};
Type parametrizedDict = dict.MakeGenericType(parameters);
object result = Activator.CreateInstance(parametrizedDict);
Upvotes: 3
Reputation: 1542
Use generics if type is known at compile time:
void Main()
{
var dict = CreateDict<int>();
dict["key"] = 10;
}
Dictionary<string, T> CreateDict<T>()
{
return new Dictionary<string, T>();
}
If not, refactor to use a base type or interface e.g:
var dic = new Dictionary<string, IMyType>();
where IMyType exposes the common traits of the type that you wish to keep in the dictionary.
Only as a last resort would I look to reflection.
Upvotes: 1
Reputation: 12629
It can be done if you pass type as a parameter:
var dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string),type);
var dictionary = (IDictionary)Activator.CreateInstance(dictionaryType);
usage of such dictionary will be harder due to you take full responsibility on correctness of what is inserted to this dictionary.
Upvotes: 4
Reputation: 2921
all instances and classes are objects, so why not Dictionary<string,object>
and you do cast the same way you do with ViewData in MVC, Session or Cache, all of them need the cast.
Upvotes: 1