As other people mentioned, this situation is very usual and definitely requires a context to solve it from a better perspective, as I suspect a bad architecture of the code base. Nonetheless, your question remains valid. To solve it, you have at least two possibilities:
1. Require development time; negligible time at runtime - Simply create a function that maps a given dictionary to an instance of your class. Example:
Foo MapDictionaryToFoo(IReadOnlyDictionary<string, dynamic> d)
{
return new Foo
{
ID1 = d[nameof(Foo.ID1)],
ID2 = d[nameof(Foo.ID2)],
ID3 = d[nameof(Foo.ID3)]
};
}
Example of call:
Foo myFoo = MapDictionaryToFoo(myDictionary);
2. Require runtime time; negligible development time - Create a function that maps a given dictionary to an arbitrary class, typically using Reflection. The example below assumes your class has a default constructor, therefore acting as a factory as well. If this is not the case, an existing instance can be passed in an additional parameter:
T CreateFromDictionary<T>(IReadOnlyDictionary<string, dynamic> d) where T : new()
{
T obj = new T();
foreach (var propertyInfo in typeof(T).GetProperties())
{
propertyInfo.SetValue(obj, d[propertyInfo.Name]);
}
return obj;
}
Example of call:
Foo myFoo = CreateFromDictionary<Foo>(myDictionary);
If I have to pick one, I would choose the first approach, as I avoid any Reflection, that is time consuming at runtime.