Search code examples
c#dynamic-class-creation

How to create a class from a Dictionary in C#?


I have written a method which creates a Dictionary. I need to convert this dictionary to a class.

Example of Dictionary

 Dictionary<string, dynamic> myDictionary = new Dictionary<string, dynamic> {
            { "ID1", 12 },
            { "ID2", "Text2"},
            { "ID3", "Text3" }
        };

and this is the sample of the class which needs to be created:

public class Foo
    {
        public int ID1 { get; set; }
        public string ID2 { get; set; }
        public string ID3 { get; set; }
    }

Solution

  • Your requirements are not clearly stated, but I'm guessing you are looking for a dynamic type that has properties whose names map to dictionary keys.

    In that case you can use a simple dictionary wrapper like this one:

    class DynamicDictionaryWrapper : DynamicObject
    {
        protected readonly Dictionary<string,object> _source;
        
        public DynamicDictionaryWrapper(Dictionary<string,object> source)
        {
            _source = source;
        }
    
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = null;
            return (_source.TryGetValue(binder.Name, out result));
        }
    }
    

    Which you can use this way:

    public static void Main()
    {
        var myDictionary = new Dictionary<string, dynamic> {
            { "ID1", 12 },
            { "ID2", "Text2"},
            { "ID3", "Text3" }
        };  
        dynamic myObject = new DynamicDictionaryWrapper(myDictionary);
        
        Console.WriteLine(myObject.ID1);
        Console.WriteLine(myObject.ID2);
        Console.WriteLine(myObject.ID3);
    }
    

    Output:

    12
    Text2
    Text3
    

    Link to working example on DotNetFiddle