Dynamic Class creation and access class properties c#

2.8k views Asked by At

I want to create a class dynamically and add properties to that class dynamically and after that I want to create a object of that class and Generic list of that class and access it something like this : enter image description here

3

There are 3 answers

1
Dennis Larisch On

You can create a List of your class with:

List<ClassA> list = new List<ClassA>();

And add your created object of that class to The List with:

list.Add(dynamic);
0
LeD On

If you simply want the data in an undefined format, you could use Dictionary
Ex:
Dictionary < string, object > param = new Dictionary< string, object>();
param.Add("msg", "hello");
param.Add("number", 1234);

Later could be accessible as:
param["msg"] as string
param["number"] as int

0
Jeroen van Langen On

Microsoft released a library for creating dynamic linq queries. There is a ClassFactory which can be used to create classes at runtime.

Here's an example:

class Program
{
    static void SetPropertyValue(object instance, string name, object value)
    {
        // this is just for example, it would be wise to cache the PropertyInfo's
        instance.GetType().GetProperty(name)?.SetValue(instance, value);
    }

    static void Main(string[] args)
    {
        // create an enumerable which defines the properties
        var properties = new[]
        {
            new DynamicProperty("Name", typeof(string)),
            new DynamicProperty("Age", typeof(int)),
        };

        // create the class type
        var myClassType = ClassFactory.Instance.GetDynamicClass(properties);

        // define a List<YourClass> type.
        var myListType = typeof(List<>).MakeGenericType(myClassType);

        // create an instance of the list
        var myList = (IList)Activator.CreateInstance(myListType);

        // create an instance of an item
        var first = Activator.CreateInstance(myClassType);

        // use the method above to fill the properties
        SetPropertyValue(first, "Name", "John");
        SetPropertyValue(first, "Age", 24);

        // add it to the list
        myList.Add(first);


        var second = Activator.CreateInstance(myClassType);

        SetPropertyValue(second, "Name", "Peter");
        SetPropertyValue(second, "Age", 38);

        myList.Add(second);
    }
}

You can download it here: DynamicLibrary.cs