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 :

Dynamic Class creation and access class properties c#
2.8k views Asked by Abhay At
3
There are 3 answers
0
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
You can create a List of your class with:
And add your created object of that class to The List with: