Class DynamicClassFactory
A factory to create dynamic classes, based on http://stackoverflow.com/questions/29413942/c-sharp-anonymous-object-with-properties-from-dictionary.
Inheritance
Inherited Members
Namespace: System.Linq.Dynamic.Core
Assembly: System.Linq.Dynamic.Core.dll
Syntax
public static class DynamicClassFactory
Methods
| Improve this Doc View SourceCreateGenericComparerType(Type, Type)
Create a GenericComparerType based on the GenericType and an instance of a System.Collections.IComparer.
Declaration
public static Type CreateGenericComparerType(Type comparerGenericType, Type comparerType)
Parameters
Type | Name | Description |
---|---|---|
System.Type | comparerGenericType | The GenericType |
System.Type | comparerType | The System.Collections.IComparer instance |
Returns
Type | Description |
---|---|
System.Type | Type |
CreateType(IList<DynamicProperty>, Boolean)
The CreateType method creates a new data class with a given set of public properties and returns the System.Type object for the newly created class. If a data class with an identical sequence of properties has already been created, the System.Type object for this class is returned.
Data classes implement private instance variables and read/write property accessors for the specified properties.Data classes also override the Equals and GetHashCode members to implement by-value equality.
Data classes are created in an in-memory assembly in the current application domain. All data classes inherit from DynamicClass and are given automatically generated names that should be considered private (the names will be unique within the application domain but not across multiple invocations of the application). Note that once created, a data class stays in memory for the lifetime of the current application domain. There is currently no way to unload a dynamically created data class.
The dynamic expression parser uses the CreateClass methods to generate classes from data object initializers. This feature in turn is often used with the dynamic Select method to create projections.
Declaration
public static Type CreateType(IList<DynamicProperty> properties, bool createParameterCtor = true)
Parameters
Type | Name | Description |
---|---|---|
System.Collections.Generic.IList<DynamicProperty> | properties | The DynamicProperties |
System.Boolean | createParameterCtor | Create a constructor with parameters. Default set to true. Note that for Linq-to-Database objects, this needs to be set to false. |
Returns
Type | Description |
---|---|
System.Type | Type |
Examples
DynamicProperty[] props = new DynamicProperty[] { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) };
Type type = DynamicClassFactory.CreateType(props);
DynamicClass dynamicClass = (DynamicClass) Activator.CreateInstance(type)!;
dynamicClass.SetDynamicPropertyValue("Name", "Albert");
dynamicClass.SetDynamicPropertyValue("Birthday", new DateTime(1879, 3, 14));