converting object to dictionary c# code example

Example: convert dictionary to object c#

class ObjectToMapTo
        {
            public int ID;
            public string Name;
            public bool IsAdmin;

            public override string ToString()
            {
                return $"(ID={ID} Name={Name} IsAdmin={IsAdmin})";
            }

        }


        static object MapDictToObj(Dictionary<string, object> dict, Type destObject)
        {

            object returnobj = Activator.CreateInstance(destObject);

            foreach (string key in dict.Keys)
            {
                object value = dict[key];

                FieldInfo field = destObject.GetField(key);
                if (field != null)
                {
                    field.SetValue(returnobj, value);
                }


            }

            return returnobj;
        }



        static void Main(string[] args)
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict["ID"] = 1000;
            dict["Name"] = "This is a name";
            dict["IsAdmin"] = true;

            ObjectToMapTo obj = (ObjectToMapTo)MapDictToObj(dict, typeof(ObjectToMapTo));

            Console.WriteLine(obj);

            Console.ReadKey();
            //Returns: (ID=1000 Name=This is a name IsAdmin=True)

        }

Tags:

Misc Example