Suppose I have Dictionary like this:
Dictionary<string, string> values = new Dictionary<string, string>()
{
{ "Name" , "John Smith"},
{ "Age", "34"}
};
Now I want to create type from that dictionary and initialize it with values in run-time so that I was able to access it’s properties with reflection.
For this example I want object with property Name equals to "Jon Smith" and Age equals to 34.
Edit:
I need this to compare two objects with semantic comparison library such as TestApi. First object created by other code that has strong type
class Person
{
public string Name {get; set;}
public int Age { get; set;}
}
and other I need to create from other source like xml file (but not necessary). Types that would be compared are known only in run-time.
If you’re using C# 4 you could use
dynamicandExpandoObjectfor this – it’s not actually creating a new type, but it’s close enough in some cases:EDIT: I missed that you wanted to access the data with reflection. Using reflection is a way of effectively treating the type like a map – and you’ve already got it in that form. Why not just access the dictionary directly? The only benefit would be if you wanted to be able to use some types with reflection, and some with a dictionary. In that case I’d create a general-purpose interface with two implementations – one of which got values from a dictionary, and one of which used reflection. That’s going to be a lot easier than creating a type on the fly (which is possible, but not a lot of fun).