Class DynamicClassFactory
A factory to create dynamic classes, based on http://stackoverflow.com/questions/29413942/c-sharp-anonymous-object-with-properties-from-dictionary.
public static class DynamicClassFactory
- Inheritance
-
DynamicClassFactory
- Inherited Members
Methods
CreateType(IList<DynamicProperty>, Type?, string?)
Dynamically creates a new class type with a given set of public properties.
public static Type CreateType(IList<DynamicProperty> properties, Type? parentType = null, string? typeName = null)
Parameters
properties
IList<DynamicProperty>The DynamicProperties
parentType
TypeThe type to inherit from, defaults to null
typeName
stringoptional typeName
Returns
Examples
DynamicProperty[] props= new DynamicProperty[] { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) };
Type type= DynamicClassFactory.CreateType(props);
dynamic dynamicClass= Activator.CreateInstance(type) as DynamicClass;
dynamicClass.Name= "Albert";
dynamicClass.Birthday= new DateTime(1879, 3, 14);
Console.WriteLine(dynamicClass);
Remarks
If a data class with an identical sequence of properties has already been created, the System.Type object for this already created class is returned. The generated classes
Note that once created, a generated class stays in memory for the lifetime of the current application. There is currently no way to unload a dynamically created class.