Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# reflection dictionary

say I have this code:

Dictionary<String, String> myDictionary = new Dictionary<String, String>();
Type[] arguments = myDictionary.GetType().GetGenericArguments();

In my program, myDictionary it's of unknown types (it's an object returned from a deserialized XML), but for the purpose of this question, they are string. I want to create something like this:

Dictionary<arguments[0],arguments[1]> mySecondDictionary = new Dictionary<arguments[0],arguments[1]>();

Obviously, it doesn't work. I searched on MSDN, and I saw they are using the Activator class, but I don't get it. Maybe somebody more advanced, could help me a little.

like image 986
user2536272 Avatar asked Sep 15 '25 06:09

user2536272


1 Answers

You can use the activator class like you mentioned in order to create objects from given types. The MakeGenericType method allows you to specify an array of Types as the parameters for generic objects, which is what you were trying to simulate.

Dictionary<String, String> myDictionary = new Dictionary<String, String>();
Type[] arguments = myDictionary.GetType().GetGenericArguments();

Type dictToCreate = typeof(Dictionary<,>).MakeGenericType(arguments);
var mySecondDictionary = Activator.CreateInstance(dictToCreate);

The code above is essentially pointless as you know that the dictionary is String,String beforehand but assuming you have a way of detecting the required types elsewhere during runtime, you can use the last two lines to instantiate a dictionary of that type.

like image 94
keyboardP Avatar answered Sep 17 '25 21:09

keyboardP