Fill a dictionary with properties of a class

Lets come to the most importan class in all this, the “ObjectExtensions” it has 2 functions, one the transfers all the properties of a given class into a IDictionary<string,object> and one that transfers all the Dictionary Key-Value pairs to a given class.

Function “ObjectFromDictionary<t>()”

The function takes a class and a Dictionary and tranfsers all the Key-Value pairs onto the properties of the given class.

But be careful, Boolean, int, float, long, Arrays, Lists, etc. have to be cast as can be seen in the example. My Configuration Class uses a few booleans and their value is saved as string in the dictionary.

If an item can not be transfered a “System.Reflection.TargetException: ‘Object does not match target type.'” is thrown!

Function: ObjectToDictionary<T>()

This function takes a class and transfers all the properties into a dictionary in a key-value matter and then returns the dictionary for use.

Here you go.

Idea and most of the reflection work was done on stackoverflow 😉

Post on Stackoverflow: https://stackoverflow.com/a/4944155

Thread on Stackoverflow: https://stackoverflow.com/questions/4943817/mapping-object-to-dictionary-and-vice-versa

On the next page is the source-code of both classes 🙂

This entry was posted in C#, PC, programming, Sonstiges, Wissen, Work and tagged , , , , . Bookmark the permalink.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.