Home > Back-end >  How can I create an object in C# during program execution, specify the type and assign a value?
How can I create an object in C# during program execution, specify the type and assign a value?

Time:05-09

Help me, is it possible in C# to make a dynamically created class whose number of properties and their types are not known in advance?

For example, there is a POCO class and it is necessary to load a file template (for example - XML) when loading, in which the names of objects (properties), their types and values will be specified.

It seems to me that this can be done through a dictionary and a wrapper class (maybe I'm wrong and this is a bad decision). But I can't figure out how to dynamically unpack from object to the correct realy class without creating dozens of as conditions?

public static class Program
{
    public static void Main()
    {
        Dictionary<string, ElemType> keys = new Dictionary<string, ElemType>();
        keys.Add(
            "UserID", new ElemType() { NameType = "System.Int32", ValueType = "123" }
            );
        keys.Add(
            "UserName", new ElemType() { NameType = "System.String", ValueType = "abc" }
            );

        var type = Type.GetType(keys["UserID"].NameType);
        ///var elem = (???type)Activator.CreateInstance(type);
    }
}

public class ElemType
{
    public string NameType { get; set; }
    public object ValueType { get; set; }
}

CodePudding user response:

You can use an ExpandObject which can define properties during the runtime. Below is a very simple working prototype

    static void Main(string[] args)
    {
        // Define a type with the following properties
        //  string  Name
        //  int     Age
        //  bool    Alive


        dynamic test2 = CreateInstance(
            ("Name", "John"),
            ("Age", 50),
            ("Alive", true));

        Console.WriteLine($"Name:{test2.Name} Age:{test2.Age}");
    }

    static dynamic CreateInstance(params (string name, object value)[] properties)
    {
        dynamic eo = new ExpandoObject();
        var dict = (IDictionary<string, object>)eo;

        foreach (var item in properties)
        {
            dict[item.name] = item.value;
        }

        return eo;
    }
  • Related