### Instance Creation Example Source: https://github.com/buunguyen/fasterflect/wiki/Advanced-Object-Construction An example demonstrating how to create an instance of a class using TryCreateInstance with a sample object. ```APIDOC ## Instance Creation Example ### Description This example shows how to create an instance of the `Lion` class using `TryCreateInstance` by providing a sample object with properties that match the constructor parameters. ### Method `TryCreateInstance` ### Endpoint `typeof(Lion).TryCreateInstance( new { id=42, name="Scar", age=4 } )` ### Request Example ```csharp public class Lion { public int Id { get; private set; } public string Name { get; private set; } public Lion( int id, string name ) { Id = id; Name = name; } } // creating an instance is a simple one-step process - TryCreateInstance does all the work Lion animal = typeof(Lion).TryCreateInstance( new { id=42, name="Scar", age=4 } ) as Lion; ``` ``` -------------------------------- ### Type Conversion Example with XML Source: https://github.com/buunguyen/fasterflect/wiki/Advanced-Object-Construction An example illustrating the power of built-in type conversions using XML input. ```APIDOC ## Type Conversion Example with XML ### Description This example illustrates some of the power of having these type conversions built in, using an XML structure as input. ### Request Example ```csharp // lets whip up a quick XElement structure that we use as input XElement xml = new XElement( "Books", new XElement( "Book", new XAttribute( "id", 1 ), new XAttribute( "author", "Douglad Adams" ), new XAttribute( "title", "The Hitchhikers Guide to the Galaxy" ), new XAttribute( "rating", 4.8 ) ) ); // since we're creating known types we need a corresponding Book class private class Book { private int _id; // observe that this field is not on the constructor below and contains a leading underscore public string Author { get; private set; } ``` ``` -------------------------------- ### FieldInfo Usage Example Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Access Shows how to use FieldInfo extensions in conjunction with the Fasterflect Querying API. ```C# Type type = typeof(Person); FieldInfo staticField = type.Field("staticIntField", Flags.StaticAnyVisibility); staticField.Set(10); int val = (int)staticField.Get(); FieldInfo field = type.Field("name"); var person = type.CreateInstance(); field.Set(person, "tommy"); string name = (string)field.Get(person); ``` -------------------------------- ### Invoke Constructor Delegate Source: https://github.com/buunguyen/fasterflect/wiki/Using-Delegates Example of creating a constructor delegate and using it to instantiate objects within a loop. ```C# // Create the delegate to the 1-string-argument constructor of class Person // CIL for the delegate is generated now, if not already generated var ctor = typeof(Person).DelegateForCreateInstance(typeof(string)); while (longLoop) { object person = ctor(name); // almost as fast as native constructor invocation } ``` -------------------------------- ### Object Construction Benchmark Example Source: https://github.com/buunguyen/fasterflect/wiki/Benchmarks Demonstrates how to use the utility methods to benchmark object construction via direct instantiation, reflection, and Fasterflect. Requires Person type and relevant Fasterflect extensions. ```C# private static void RunConstructorBenchmark() { ConstructorInfo ctorInfo = null; ConstructorInvoker invoker = null; var initMap = new Dictionary { { "Init info", () => { ctorInfo = typeof(Person).GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null ); } }, { "Init ctorInvoker", () => { invoker = typeof(Person).DelegateForCreateInstance(); } }, }; var actionMap = new Dictionary { { "Direct ctor", () => new Person() }, { "Reflection ctor", () => ctorInfo.Invoke( NoArgArray ) }, { "Fasterflect ctor", () => typeof(Person).CreateInstance() }, { "Fasterflect cached ctor", () => invoker( NoArgArray ) }, }; Execute( "Benchmark for Object Construction", initMap, actionMap ); } ``` -------------------------------- ### Sample MethodInfo Invocation Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Access Shows how to get a MethodInfo object and then invoke the method directly on an instance. This approach can be more efficient if the method is invoked multiple times. ```C# var methodInfo = typeof(Employee).Method( "Walk", new [] { typeof(int) }, Flags.InstanceAnyVisibility ); var employee = typeof(Employee).CreateInstance(); methodInfo.Call(employee, 10d); // walk 10 meters ``` -------------------------------- ### Fasterflect Constructor Overloads Source: https://github.com/buunguyen/fasterflect/wiki/Object-Construction These overloads provide flexible ways to create instances of types, supporting various parameter combinations and binding flags. Ensure you have read the Getting Started guide for details on binding flags. ```C# object CreateInstance( this Type type, params object[] parameters ); ``` ```C# object CreateInstance( this Type type, Flags bindingFlags, params object[] parameters ); ``` ```C# object CreateInstance( this Type type, Type[] parameterTypes, params object[] parameters ); ``` ```C# object CreateInstance( this Type type, Type[] parameterTypes, Flags bindingFlags, params object[] parameters ); ``` ```C# object CreateInstance( this ConstructorInfo ctorInfo, params object[] parameters ); ``` -------------------------------- ### Locate Default and Parameterized Constructors Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Queries Examples showing how to locate the default constructor for a type and a constructor that expects a specific parameter list (int and string). ```C# Type type = obj.GetType(); // example showing how to locate the default constructor for a type ConstructorInfo constructor = type.Constructor(); // example showing how to locate a constructor expecting a specific parameter list constructor = type.Constructor( typeof(int), typeof(string) ); ``` -------------------------------- ### Deep Cloning with Cyclic References Source: https://github.com/buunguyen/fasterflect/wiki/Deep-Cloning Example demonstrating how to use DeepClone on an object graph containing cyclic references. ```C# // here's a classic example of a class that could be used to create an object graph with cyclic references: public class Employee { public string Name { get; private set; } public Employee Manager { get; set; } // we need a default constructor for DeepClone to work public Employee() {} // observe that passing in null for the manager will make this employee his/her own manager public Employee( string name, Employee manager ) { Name = name; Manager = manager ?? this; } } // now lets create an example object for testing the DeepClone method var employee = new Employee( "Ford Prefect", null ); var clone = employee.DeepClone(); // let's verify that the graph has been cloned correctly Assert.AreNotSame( employee, clone ); Assert.AreEqual( employee.Name, clone.Name ); Assert.AreNotSame( employee.Manager, clone.Manager ); Assert.AreSame( clone, clone.Manager ); ``` -------------------------------- ### Try Access Field Usage Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Access Example of using safe field access methods to handle potentially missing fields. ```C# var person = typeof(Person).CreateInstance(); if (person.TrySetFieldValue("someField", 20)) { // return false if not successful for some reason int val = (int) person.TryGetFieldValue("someField"); // return null if not successful for some reason } ``` -------------------------------- ### Find Readable String Fields and Properties Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Queries Example demonstrating how to find all readable instance fields and properties of type string on a given object's type. ```C# Type type = obj.GetType(); // example showing how to find all readable instance fields and properties of type string IList fieldsAndProperties = type.FieldsAndProperties().Where( m => m.IsReadable() && m.Type() == typeof(string) ).ToList(); ``` -------------------------------- ### Retrieve Method Parameters Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Queries Get the list of parameters for a given method or constructor. This is useful for inspecting method signatures. ```C# IList Parameters( this MethodBase method ); ``` -------------------------------- ### Map Object Members - Usage Examples Source: https://github.com/buunguyen/fasterflect/wiki/Object-Mapping Illustrates various ways to use the Map method for copying member values between objects, including mapping all members, selected members, and handling anonymous types. ```C# // example showing how one might use the Map method var source = new { ID=42, Name="Arthur Dent" }; var target = new Person(); // maps all members (ignoring case as sourceMemberTypes != targetMemberTypes) source.Map( target, MemberTypes.Properties, MemberTypes.Fields, Flags.InstanceAnyVisibility ); // maps selected members (respecting case as sourceMemberTypes == targetMemberTypes) source.Map( target, MemberTypes.Properties, MemberTypes.Properties, Flags.InstanceAnyVisibility, "ID", "Name" ); // maps all members (ignoring case as sourceMemberTypes != targetMemberTypes) source.Map( target, MemberTypes.Properties, MemberTypes.Fields | MemberTypes.Properties, Flags.InstanceAnyVisibility ); // the special case of using an anonymous source for which no variable has been declared can look odd new { ID=42, Name="Arthur Dent" }.Map( target, MemberTypes.Properties, MemberTypes.Fields, Flags.InstanceAnyVisibility ); // this can be made more readable by calling the extension method the old-fashioned way MapExtensions.Map( new { ID=42, Name="Arthur Dent" }, target, MemberTypes.Properties, MemberTypes.Fields, Flags.InstanceAnyVisibility ); ``` -------------------------------- ### Using Fasterflect with Structs Example Source: https://github.com/buunguyen/fasterflect/wiki/Working-with-Structs Demonstrates the typical workflow for using Fasterflect with types that might be structs. Wrap the object if it's a struct, perform operations, and then unwrap it. ```C# var obj = typeof(SomeTypeWhichMightBeStruct).CreateInstance(); var wrapped = obj.WrapIfValueType(); // wrap in case it's struct type, no effect if it's not wrapped.SetFieldValue("afield", 10); // now, just use what you've already know about Fasterflect to access the object's members // more Fasterflect operations on struct here... obj = wrapped.UnwrapIfWrapped(); // when you finish, do this to get back the original struct, no effect if it's not a struct type ``` -------------------------------- ### Define a concrete invocator class Source: https://github.com/buunguyen/fasterflect/wiki/Accessing Example of a non-reflective class structure that could be generated at runtime to improve invocation performance. ```C# public class ConcreteInvocator : GenericInvocator { public object Invoke(object target) { var person = (Person)target; return target.GetName(); } } ``` -------------------------------- ### Pretty Printing Type Names Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Queries Examples of using the Name extension method to format various types, including generics and nullable types. ```C# typeof( Int32 ).Name(); // returns "int" typeof( List> ).Name(); // returns "List" typeof( IList ).Name(); // returns "IList" ``` -------------------------------- ### Get/Set Field Delegates in C# Source: https://github.com/buunguyen/fasterflect/wiki/Using-Delegates Use these extension methods to create delegates for getting and setting field values. The delegates can be reused for performance. ```csharp MemberGetter DelegateForGetFieldValue( this Type type, string name ); MemberGetter DelegateForGetFieldValue( this Type type, string name, Flags bindingFlags ); MemberSetter DelegateForSetFieldValue( this Type type, string name ); MemberSetter DelegateForSetFieldValue( this Type type, string name, Flags bindingFlags ); StaticMemberGetter DelegateForGetStaticFieldValue( this Type type, string name ); StaticMemberGetter DelegateForGetStaticFieldValue( this Type type, string name, Flags bindingFlags ); StaticMemberSetter DelegateForSetStaticFieldValue( this Type type, string name ); StaticMemberSetter DelegateForSetStaticFieldValue( this Type type, string name, Flags bindingFlags ); MemberGetter DelegateForGetFieldValue( this FieldInfo fieldInfo ); MemberSetter DelegateForSetFieldValue( this FieldInfo fieldInfo ); StaticMemberGetter DelegateForGetStaticFieldValue( this FieldInfo fieldInfo ); StaticMemberSetter DelegateForSetStaticFieldValue( this FieldInfo fieldInfo ); ``` ```csharp var type = typeof(Person); MemberSetter setter = type.DelegateForSetFieldValue("name"); MemberGetter getter = type.DelegateForGetFieldValue("name"); var person = type.CreateInstance(); // the delegates are reused through all iterations while (longLoop) { setter(person, name); name = getter(person); } ``` -------------------------------- ### Sample Usages of CreateInstance Source: https://github.com/buunguyen/fasterflect/wiki/Object-Construction Demonstrates practical application of Fasterflect's CreateInstance method for creating arrays and objects with specified arguments. It also shows how to look up a constructor via ConstructorInfo before creating an instance. ```C# // Create a Person array of 15 elements var array = typeof(Person[]).CreateInstance(15); ``` ```C# // Create a person object with one argument var person = typeof(Person).CreateInstance("name"); ``` ```C# // Create a person via ConstructorInfo var ctorInfo = typeof(Person).Constructor(new Type[] {typeof(string)}); // lookup the constructor person = ctorInfo.CreateInstance("name"); ``` -------------------------------- ### CreateInstance via ConstructorInfo Source: https://github.com/buunguyen/fasterflect/wiki/Object-Construction Shows how to use `CreateInstance` with `ConstructorInfo` to directly invoke a specific constructor. ```APIDOC ## CreateInstance via ConstructorInfo ### Description This method allows you to create an instance of a type by directly using a `ConstructorInfo` object, providing a way to trigger the Fasterflect engine from existing constructor information. ### Method `object CreateInstance(this ConstructorInfo ctorInfo, params object[] parameters)` ### Endpoint N/A (Extension Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```csharp // Lookup the constructor that takes a string argument var ctorInfo = typeof(Person).Constructor(new Type[] {typeof(string)}); // Create a person object using the ConstructorInfo var person = ctorInfo.CreateInstance("name"); ``` ### Response #### Success Response (200) - **object** - An instance of the type associated with the `ConstructorInfo`. ``` -------------------------------- ### Accessing Array Elements Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Access Methods for getting and setting elements in arrays dynamically. ```C# object GetElement( object array, long index ); object SetElement( object array, long index, object value ); ``` ```C# // create an array of 10 elements for the given type var array = typeof(int[]).CreateInstance(10); // set 15 to the array element at index 1th array.SetElement(1, 15); // get the value of array element at index 1th int value = (int) array.GetElement(1); ``` -------------------------------- ### Object Creation and Manipulation with Fasterflect Source: https://github.com/buunguyen/fasterflect/blob/master/README.md Demonstrates creating instances, setting/getting fields and properties, invoking indexers and methods, and mapping properties using Fasterflect. ```csharp AssertTrue(2 == (int)arguments[0]); AssertTrue(1 == (int)arguments[1]); // Now, invoke the 2-arg constructor. We don't even have to specify parameter types // if we know that the arguments are not null (Fasterflect will call arg[n].GetType() internally). obj = type.CreateInstance(1, "Doe"); // id and name should have been set properly AssertTrue(1 == (int)obj.GetFieldValue("id")); AssertTrue("Doe" == obj.GetPropertyValue("Name").ToString()); // Let's use the indexer to retrieve the character at index 1 AssertTrue('o' == (char)obj.GetIndexer(1)); // If there's null argument, or when we're unsure whether there's a null argument // we must explicitly specify the param type array obj = type.CreateInstance( new[] { typeof(int), typeof(string) }, 1, null ); // id and name should have been set properly AssertTrue(1 == (int)obj.GetFieldValue("id")); AssertTrue(null == obj.GetPropertyValue("Name")); // Now, modify the id obj.SetFieldValue("id", 2); AssertTrue(2 == (int)obj.GetFieldValue("id")); AssertTrue(2 == (int)obj.GetPropertyValue("Id")); // We can chain calls obj.SetFieldValue("id", 3) .SetPropertyValue("Name", "Buu"); AssertTrue(3 == (int)obj.GetPropertyValue("Id")); AssertTrue("Buu" == (string)obj.GetPropertyValue("Name")); // Map a set of properties from a source to a target new { Id = 4, Name = "Nguyen" }.MapProperties( obj ); AssertTrue(4 == (int)obj.GetPropertyValue("Id")); AssertTrue("Nguyen" == (string)obj.GetPropertyValue("Name")); // Let's have the folk walk 6 miles obj.CallMethod("Walk", 6); // Double-check the current value of the milesTravelled field AssertTrue(6 == (int)obj.GetFieldValue("milesTraveled")); // Construct an array of 10 elements for current type var arr = type.MakeArrayType().CreateInstance(10); // GetValue & set element of array obj = type.CreateInstance(); arr.SetElement(4, obj) .SetElement(9, obj); AssertTrue(obj == arr.GetElement(4)); AssertTrue(obj == arr.GetElement(9)); AssertTrue(null == arr.GetElement(0)); ``` -------------------------------- ### Array Access Delegates Source: https://github.com/buunguyen/fasterflect/wiki/Using-Delegates Methods to retrieve delegates for getting or setting array elements. ```APIDOC ## Array Access Methods ### Description Retrieves delegates for accessing elements within an array. ### Methods - DelegateForGetElement(Type) - DelegateForSetElement(Type) ``` -------------------------------- ### Indexer Access Delegates Source: https://github.com/buunguyen/fasterflect/wiki/Using-Delegates Methods to retrieve delegates for getting or setting indexer values. ```APIDOC ## Indexer Access Methods ### Description Retrieves MethodInvoker delegates for accessing indexers on a type. ### Methods - DelegateForGetIndexer(Type, [Flags], params Type[]) - DelegateForSetIndexer(Type, [Flags], params Type[]) ``` -------------------------------- ### Sample Method Invocation Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Access Demonstrates invoking static and instance methods, including methods with and without parameters. Ensure the correct parameter types are provided when necessary. ```C# var type = typeof(Employee); int totalEmployeeInstances = (int) type.CallMethod("GetTotalEmployeeInstances"); // invoke static method var employee = type.CreateInstance(); double salary = (double) employee.CallMethod("CalculateSalary"); // invoke method with one argument employee.CallMethod("SetTitle", "Engineer"); employee.CallMethod("SetTitle", new Type[] {typeof(string)}, mightBeNullTitleValue); ``` -------------------------------- ### Instantiating a Class with TryCreateInstance Source: https://github.com/buunguyen/fasterflect/wiki/Advanced-Object-Construction Demonstrates creating an instance of a class using an anonymous object as the input source. ```C# // lets assume we want to create an instance of the following class public class Lion { public int Id { get; private set; } public string Name { get; private set; } public Lion( int id, string name ) { Id = id; Name = name; } } // creating an instance is a simple one-step process - TryCreateInstance does all the work Lion animal = typeof(Lion).TryCreateInstance( new { id=42, name="Scar", age=4 } ) as Lion; ``` -------------------------------- ### Property Access Delegates Source: https://github.com/buunguyen/fasterflect/wiki/Using-Delegates Methods to retrieve delegates for getting or setting instance and static property values. ```APIDOC ## Property Access Methods ### Description Retrieves delegates for getting or setting property values on a type or via PropertyInfo. ### Methods - DelegateForGetPropertyValue(Type, string, [Flags]) - DelegateForGetStaticPropertyValue(Type, string, [Flags]) - DelegateForSetPropertyValue(Type, string, [Flags]) - DelegateForSetStaticPropertyValue(Type, string, [Flags]) - DelegateForGetPropertyValue(PropertyInfo) - DelegateForSetPropertyValue(PropertyInfo) - DelegateForGetStaticPropertyValue(PropertyInfo) - DelegateForSetStaticPropertyValue(PropertyInfo) ``` -------------------------------- ### Instantiating from XElement Source: https://github.com/buunguyen/fasterflect/wiki/Advanced-Object-Construction Shows how to use XML elements as input for object creation, leveraging automatic type conversion. ```C# // lets whip up a quick XElement structure that we use as input XElement xml = new XElement( "Books", new XElement( "Book", new XAttribute( "id", 1 ), new XAttribute( "author", "Douglad Adams" ), new XAttribute( "title", "The Hitchhikers Guide to the Galaxy" ), new XAttribute( "rating", 4.8 ) ) ); // since we're creating known types we need a corresponding Book class private class Book { private int _id; // observe that this field is not on the constructor below and contains a leading underscore public string Author { get; private set; } ``` -------------------------------- ### Create Book Instances with TryCreateInstance Source: https://github.com/buunguyen/fasterflect/wiki/Advanced-Object-Construction Uses Fasterflect's TryCreateInstance to dynamically create Book objects from XML data. Ensure the Book class and necessary Fasterflect extensions are available. ```csharp // finally the real action begins - first step is to select the data we want to feed to TryCreateInstance var data = from book in xml.Elements("Book") select new { id=book.Attribute("id"), author=book.Attribute("author"), title=book.Attribute("title"), rating=book.Attribute("rating") }; // did you notice that we just grabbed the attributes without selecting the Value property? // the final step is to create some book instances IList books = data.Select( b => typeof(Book).TryCreateInstance( b ) as Book ).ToList(); // we'll verify the results to make sure we got what we expected Assert.AreEqual( 1, books.Count ); Assert.AreEqual( 1, books[ 0 ].GetFieldValue( "_id" ) ); Assert.AreEqual( "Douglad Adams", books[ 0 ].Author ); Assert.AreEqual( "The Hitchhikers Guide to the Galaxy", books[ 0 ].Title ); Assert.AreEqual( 4.8, books[ 0 ].Rating ); ``` -------------------------------- ### Field Access Delegates Source: https://github.com/buunguyen/fasterflect/wiki/Using-Delegates Methods to retrieve delegates for getting or setting instance and static field values. ```APIDOC ## Field Access Methods ### Description Retrieves delegates for getting or setting field values on a type or via FieldInfo. ### Methods - DelegateForGetFieldValue(Type, string, [Flags]) - DelegateForSetFieldValue(Type, string, [Flags]) - DelegateForGetStaticFieldValue(Type, string, [Flags]) - DelegateForSetStaticFieldValue(Type, string, [Flags]) - DelegateForGetFieldValue(FieldInfo) - DelegateForSetFieldValue(FieldInfo) - DelegateForGetStaticFieldValue(FieldInfo) - DelegateForSetStaticFieldValue(FieldInfo) ``` -------------------------------- ### Standard Field Accessor Signatures Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Access Extension method signatures for getting and setting fields on Types and Objects. ```C# object GetFieldValue( this Type type, string name ); object GetFieldValue( this Type type, string name, Flags bindingFlags ); object GetFieldValue( this object obj, string name ); object GetFieldValue( this object obj, string name, Flags bindingFlags ); Type SetFieldValue( this Type type, string name, object value ); Type SetFieldValue( this Type type, string name, object value, Flags bindingFlags ); object SetFieldValue( this object obj, string name, object value ); object SetFieldValue( this object obj, string name, object value, Flags bindingFlags ); ``` -------------------------------- ### CreateInstance Overloads Source: https://github.com/buunguyen/fasterflect/wiki/Object-Construction Demonstrates the various overloads of the `CreateInstance` extension method for creating instances of reference types, struct types, and array types. ```APIDOC ## CreateInstance Overloads ### Description Fasterflect provides several overloads for the `CreateInstance` extension method to facilitate the creation of objects, arrays, and structs. These methods support specifying constructor parameters and binding flags for customized instantiation. ### Method `object CreateInstance(this Type type, params object[] parameters)` `object CreateInstance(this Type type, Flags bindingFlags, params object[] parameters)` `object CreateInstance(this Type type, Type[] parameterTypes, params object[] parameters)` `object CreateInstance(this Type type, Type[] parameterTypes, Flags bindingFlags, params object[] parameters)` ### Endpoint N/A (Extension Methods) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```csharp // Create a Person array of 15 elements var array = typeof(Person[]).CreateInstance(15); // Create a person object with one argument var person = typeof(Person).CreateInstance("name"); ``` ### Response #### Success Response (200) - **object** - An instance of the specified type. ``` -------------------------------- ### Array Element Delegates in C# Source: https://github.com/buunguyen/fasterflect/wiki/Using-Delegates Use these extension methods to obtain delegates for getting and setting elements within an array. ```csharp ArrayElementGetter DelegateForGetElement( this Type arrayType ); ArrayElementSetter DelegateForSetElement( this Type arrayType ); ``` -------------------------------- ### TryCreateInstance Overloads Source: https://github.com/buunguyen/fasterflect/wiki/Advanced-Object-Construction These extension methods allow for object instantiation using various input sources like objects, dictionaries, or explicit parameter arrays. ```C# // use the public properties from the sample object to create an instance object TryCreateInstance( this Type type, object sample ); // use the contents of the supplied dictionary to create an instance object TryCreateInstance( this Type type, IDictionary parameters ); // use the supplied names and associated values to create an instance (types are inferred from the supplied values) object TryCreateInstance( this Type type, string[] parameterNames, object[] parameterValues ); // use the supplied names and associated types and values to create an instance object TryCreateInstance( this Type type, string[] parameterNames, Type[] parameterTypes, object[] parameterValues ); ``` -------------------------------- ### Property Access Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Access Provides methods for getting and setting property values on types and objects, with support for binding flags and attempting operations. ```APIDOC ## Property Access Property accesses in Fasterflect work the same way with field accesses. As such, if you substitute GetFieldValue for GetPropertyValue and SetFieldValue for SetPropertyValue in the previous section then the exact same applies when accessing properties. ### Static Property Access #### GetPropertyValue * **Method**: `object GetPropertyValue(this Type type, string name)` * **Method**: `object GetPropertyValue(this Type type, string name, Flags bindingFlags)` ### Instance Property Access #### GetPropertyValue * **Method**: `object GetPropertyValue(this object obj, string name)` * **Method**: `object GetPropertyValue(this object obj, string name, Flags bindingFlags)` #### SetPropertyValue * **Method**: `Type SetPropertyValue(this Type type, string name, object value)` * **Method**: `Type SetPropertyValue(this Type type, string name, object value, Flags bindingFlags)` * **Method**: `object SetPropertyValue(this object obj, string name, object value)` * **Method**: `object SetPropertyValue(this object obj, string name, object value, Flags bindingFlags)` ### PropertyInfo Based Access #### Get * **Method**: `object Get(this PropertyInfo propInfo)` * **Method**: `object Get(this PropertyInfo propInfo, object obj)` #### Set * **Method**: `void Set(this PropertyInfo propInfo, object value)` * **Method**: `void Set(this PropertyInfo propInfo, object obj, object value)` ### Try Property Access #### TryGetPropertyValue * **Method**: `object TryGetPropertyValue(this object obj, string name)` * **Method**: `object TryGetPropertyValue(this object obj, string name, Flags bindingFlags)` #### TrySetPropertyValue * **Method**: `bool TrySetPropertyValue(this object obj, string name, object value)` * **Method**: `bool TrySetPropertyValue(this object obj, string name, object value, Flags bindingFlags)` ``` -------------------------------- ### Load and execute a generated assembly Source: https://github.com/buunguyen/fasterflect/wiki/Accessing Demonstrates loading a compiled assembly and invoking a method via a generated interface. ```C# object obj = Assembly.LoadFrom(generatedDll).CreateInstance("ConcreteInvocator") GenericInvocator personInvocator = obj as GenericInvocator; string name = (string)personInvocator.Invoke(personObject); ``` -------------------------------- ### Cache Property Setter and Getter Source: https://github.com/buunguyen/fasterflect/wiki/2-Minute-Guide-To-Accessing-API Caches delegates for setting and getting property values. Improves performance for repeated property access. ```csharp MemberSetter nameSetter = type.DelegateForSetPropertyValue("Name"); MemberGetter nameGetter = type.DelegateForGetPropertyValue("Name"); ``` -------------------------------- ### Constructing Objects and Accessing Members with Fasterflect Source: https://github.com/buunguyen/fasterflect/blob/master/README.md Demonstrates using Fasterflect to instantiate objects, access fields, and invoke methods, including those with ref/out parameters. ```csharp class Person { private int id; private int milesTraveled; public int Id { get { return id; } set { id = value; } } public string Name { get; private set; } private static int InstanceCount; public Person() : this(0) { } public Person(int id) : this(id, string.Empty) { } public Person(int id, string name) { Id = id; Name = name; InstanceCount++; } public char this[int index] { get { return Name[index]; } } private void Walk(int miles) { milesTraveled += miles; } private static void IncreaseInstanceCount() { InstanceCount++; } private static int GetInstanceCount() { return InstanceCount; } public static void Swap(ref int i, ref int j) { int tmp = i; i = j; j = tmp; } } class Program { static void Main() { var type = Assembly.GetExecutingAssembly().GetType( "FasterflectSample.Person" ); ExecuteNormalApi(type); ExecuteCacheApi(type); } private static void ExecuteNormalApi(Type type) { // Person.InstanceCount should be 0 since no instance is created yet AssertTrue((int)type.GetFieldValue("InstanceCount") == 0); // Invokes the no-arg constructor object obj = type.CreateInstance(); // Double-check if the constructor is invoked successfully or not AssertTrue(null != obj); // Now, Person.InstanceCount should be 1 AssertTrue(1 == (int)type.GetFieldValue("InstanceCount")); // We can bypass the constructor to change the value of Person.InstanceCount directly type.SetFieldValue("InstanceCount", 2); AssertTrue(2 == (int)type.GetFieldValue("InstanceCount")); // Let's invoke Person.IncreaseCounter() static method to increase the counter type.CallMethod("IncreaseInstanceCount"); AssertTrue(3 == (int)type.GetFieldValue("InstanceCount")); // Now, let's retrieve Person.InstanceCount via the static method GetInstanceCount AssertTrue(3 == (int)type.CallMethod("GetInstanceCount")); // Invoke method receiving ref/out params, we need to put arguments in an array var arguments = new object[] { 1, 2 }; type.CallMethod("Swap", // Parameter types must be set to the appropriate ref type new[] { typeof(int).MakeByRefType(), typeof(int).MakeByRefType() }, arguments); ``` -------------------------------- ### Accessing Properties with Fasterflect Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Access Provides extension methods for getting and setting property values, including try-get/set variants and direct PropertyInfo access. ```C# object GetPropertyValue( this Type type, string name ); object GetPropertyValue( this Type type, string name, Flags bindingFlags ); object GetPropertyValue( this object obj, string name ); object GetPropertyValue( this object obj, string name, Flags bindingFlags ); Type SetPropertyValue( this Type type, string name, object value ); Type SetPropertyValue( this Type type, string name, object value, Flags bindingFlags ); object SetPropertyValue( this object obj, string name, object value ); object SetPropertyValue( this object obj, string name, object value, Flags bindingFlags ); object Get( this PropertyInfo propInfo ); object Get( this PropertyInfo propInfo, object obj ); void Set( this PropertyInfo propInfo, object value ); void Set( this PropertyInfo propInfo, object obj, object value ); object TryGetPropertyValue( this object obj, string name ); object TryGetPropertyValue( this object obj, string name, Flags bindingFlags ); bool TrySetPropertyValue( this object obj, string name, object value ); bool TrySetPropertyValue( this object obj, string name, object value, Flags bindingFlags ); ``` -------------------------------- ### Use Cached Constructor and Getter Source: https://github.com/buunguyen/fasterflect/wiki/2-Minute-Guide-To-Accessing-API Demonstrates using a cached constructor to create objects and a cached getter to verify field values. Ensures instance counts and field values are as expected. ```csharp int currentInstanceCount = (int)count(); ConstructorInvoker ctor = type.DelegateForCreateInstance(new[] { typeof(int), typeof(string) }); range.ForEach(i => { object obj = ctor(i, "_" + i); AssertTrue(++currentInstanceCount == (int)count()); AssertTrue(i == (int)obj.GetFieldValue("id")); AssertTrue("_" + i == obj.GetPropertyValue("Name").ToString()); }); ``` -------------------------------- ### Create instances dynamically with CreateInstance Source: https://context7.com/buunguyen/fasterflect/llms.txt Use CreateInstance to instantiate reference, struct, or array types. Supports parameter type inference and direct ConstructorInfo invocation. ```csharp using Fasterflect; // Create instance using default constructor object person = typeof(Person).CreateInstance(); // Create instance with constructor arguments (type inference) object personWithName = typeof(Person).CreateInstance("John Doe"); // Create instance with explicit parameter types (required if arguments might be null) object personWithNullable = typeof(Person).CreateInstance( new[] { typeof(int), typeof(string) }, 42, null ); // Create an array of 10 elements var array = typeof(Person[]).CreateInstance(10); // Create instance via ConstructorInfo ConstructorInfo ctor = typeof(Person).Constructor(typeof(int), typeof(string)); object personViaCtor = ctor.CreateInstance(1, "Jane"); ``` -------------------------------- ### Use Cached Property Setter and Getter Source: https://github.com/buunguyen/fasterflect/wiki/2-Minute-Guide-To-Accessing-API Demonstrates using cached delegates to get and set property values on an object. Verifies that the property updates correctly. ```csharp object person = ctor(1, "John"); AssertTrue("John" == (string)nameGetter(person)); nameSetter(person, "Jane"); AssertTrue("Jane" == (string)nameGetter(person)); ``` -------------------------------- ### Convenience Methods for Field and Property Mapping Source: https://github.com/buunguyen/fasterflect/wiki/Object-Mapping Companion methods for explicit mapping between fields and properties. These methods improve code clarity by specifying the exact mapping direction. ```C# // maps fields to fields (respecting case) void MapFields( this object source, object target, params string[] names ); // maps fields to properties (ignoring case) void MapFieldsToProperties( this object source, object target, params string[] names ); // maps properties to properties (respecting case) void MapProperties( this object source, object target, params string[] names ); // maps properties to fields (ignoring case) void MapPropertiesToFields( this object source, object target, params string[] names ); ``` -------------------------------- ### Query Fields and Properties Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Queries Use these methods to locate all fields and properties on a type. The results are MemberInfo instances which can be further inspected using helper extensions. ```C# IList FieldsAndProperties( this Type type ); ``` ```C# IList FieldsAndProperties( this Type type, Flags bindingFlags ); ``` -------------------------------- ### DelegateForCreateInstance Source: https://github.com/buunguyen/fasterflect/wiki/Using-Delegates Extension methods to retrieve a ConstructorInvoker delegate for creating object instances. ```APIDOC ## DelegateForCreateInstance ### Description Retrieves a `ConstructorInvoker` delegate for a specified type, allowing for high-performance object instantiation. ### Methods - `DelegateForCreateInstance(this Type type, params Type[] parameterTypes)` - `DelegateForCreateInstance(this Type type, Flags bindingFlags, params Type[] parameterTypes)` - `DelegateForCreateInstance(this ConstructorInfo ctorInfo)` ### Request Example // Create the delegate to the 1-string-argument constructor of class Person var ctor = typeof(Person).DelegateForCreateInstance(typeof(string)); object person = ctor("John Doe"); ``` -------------------------------- ### TryCreateInstance Overloads Source: https://github.com/buunguyen/fasterflect/wiki/Advanced-Object-Construction Fasterflect provides several overloads for TryCreateInstance to create object instances by automatically figuring out the best constructor based on input values. ```APIDOC ## TryCreateInstance Overloads ### Description Fasterflect provides extensions for creating object instances where it automatically figures out how best to create the object given a set of input values. ### Method `TryCreateInstance` ### Endpoints - `object TryCreateInstance( this Type type, object sample );` - `object TryCreateInstance( this Type type, IDictionary parameters );` - `object TryCreateInstance( this Type type, string[] parameterNames, object[] parameterValues );` - `object TryCreateInstance( this Type type, string[] parameterNames, Type[] parameterTypes, object[] parameterValues );` ### Details Regardless of which overload you use, the internal logic is the same. Fasterflect will inspect the supplied parameters and try to match these to constructor parameters and writable members on the type to create. Matching is done by comparing names (ignoring case and any single leading underscore). It examines all available constructors and automatically picks the combination that allows it to use the most values from the input source, while passing as many values as possible as constructor parameters for best performance. Once found, the optimal "construction recipe" is cached for subsequent requests that use an identically shaped set of input values (that is, have the same names and types but ignoring the actual values), which ensures the best possible performance not only when creating a single instance but also when creating multiple instances. ``` -------------------------------- ### Supported Type Conversions Source: https://github.com/buunguyen/fasterflect/wiki/Advanced-Object-Construction Details on the type conversions that TryCreateInstance will attempt to make, inspired by XML data retrieval. ```APIDOC ## Supported Type Conversions ### Description If an input value of type string happens to match a parameter or member with a different data type, TryCreateInstance will try to convert the value. As an example, this feature makes it possible to supply a string input value for a parameter that is of type double, since TryCreateInstance will attempt to convert the string value before using the value. One caveat resulting from this is that the cached "construction recipe" includes information on what type conversions were performed for the first instance created. If you later pass an identical set of input values, but this time with a string that cannot be converted to double, then construction will fail. ### Type Conversion Table | Source type(s) | Target type(s) | | -------------- | -------------- | | numeric | Any other numeric type, including types that would truncate the original value (such as double to int) | | byte[16] | Guid | | string | Guid, enumeration or any numeric primitive type | | enum | string or any numeric primitive type | | XmlNode | triggers type conversion of the InnerXml (string) property | | XElement and XAttribute | triggers type conversion of the Value (string) property | ``` -------------------------------- ### Execute Reflection Operations with Fasterflect Source: https://github.com/buunguyen/fasterflect/wiki/2-Minute-Guide-To-Accessing-API Demonstrates various reflection operations using Fasterflect, including instance creation, field/property access, method invocation, and array manipulation. Ensure the 'Person' class and necessary Fasterflect extensions are available. ```C# class Program { static void Main() { var type = Assembly.GetExecutingAssembly().GetType( "FasterflectSample.Person" ); ExecuteNormalApi(type); ExecuteCacheApi(type); } private static void ExecuteNormalApi(Type type) { // Person.InstanceCount should be 0 since no instance is created yet AssertTrue((int)type.GetFieldValue("InstanceCount") == 0); // Invokes the no-arg constructor object obj = type.CreateInstance(); // Double-check if the constructor is invoked successfully or not AssertTrue(null != obj); // Now, Person.InstanceCount should be 1 AssertTrue(1 == (int)type.GetFieldValue("InstanceCount")); // We can bypass the constructor to change the value of Person.InstanceCount directly type.SetFieldValue("InstanceCount", 2); AssertTrue(2 == (int)type.GetFieldValue("InstanceCount")); // Let's invoke Person.IncreaseCounter() static method to increase the counter type.CallMethod("IncreaseInstanceCount"); AssertTrue(3 == (int)type.GetFieldValue("InstanceCount")); // Now, let's retrieve Person.InstanceCount via the static method GetInstanceCount AssertTrue(3 == (int)type.CallMethod("GetInstanceCount")); // Invoke method receiving ref/out params, we need to put arguments in an array var arguments = new object[] { 1, 2 }; type.CallMethod("Swap", // Parameter types must be set to the appropriate ref type new[] { typeof(int).MakeByRefType(), typeof(int).MakeByRefType() }, arguments); AssertTrue(2 == (int)arguments[0]); AssertTrue(1 == (int)arguments[1]); // Now, invoke the 2-arg constructor. We don't even have to specify parameter types // if we know that the arguments are not null (Fasterflect will call arg[n].GetType() internally). obj = type.CreateInstance(1, "Doe"); // id and name should have been set properly AssertTrue(1 == (int)obj.GetFieldValue("id")); AssertTrue("Doe" == obj.GetPropertyValue("Name").ToString()); // Let's use the indexer to retrieve the character at index 1 AssertTrue('o' == (char)obj.GetIndexer(1)); // If there's null argument, or when we're unsure whether there's a null argument // we must explicitly specify the param type array obj = type.CreateInstance( new[] { typeof(int), typeof(string) }, 1, null ); // id and name should have been set properly AssertTrue(1 == (int)obj.GetFieldValue("id")); AssertTrue(null == obj.GetPropertyValue("Name")); // Now, modify the id obj.SetFieldValue("id", 2); AssertTrue(2 == (int)obj.GetFieldValue("id")); AssertTrue(2 == (int)obj.GetPropertyValue("Id")); // We can chain calls obj.SetFieldValue("id", 3) .SetPropertyValue("Name", "Buu"); AssertTrue(3 == (int)obj.GetPropertyValue("Id")); AssertTrue("Buu" == (string)obj.GetPropertyValue("Name")); // Map a set of properties from a source to a target new { Id = 4, Name = "Nguyen" }.MapProperties( obj ); AssertTrue(4 == (int)obj.GetPropertyValue("Id")); AssertTrue("Nguyen" == (string)obj.GetPropertyValue("Name")); // Let's have the folk walk 6 miles obj.CallMethod("Walk", 6); // Double-check the current value of the milesTravelled field AssertTrue(6 == (int)obj.GetFieldValue("milesTraveled")); // Construct an array of 10 elements for current type var arr = type.MakeArrayType().CreateInstance(10); // GetValue & set element of array obj = type.CreateInstance(); arr.SetElement(4, obj) .SetElement(9, obj); AssertTrue(obj == arr.GetElement(4)); AssertTrue(obj == arr.GetElement(9)); AssertTrue(null == arr.GetElement(0)); } } ``` -------------------------------- ### Benchmark Measurement Utility Source: https://github.com/buunguyen/fasterflect/wiki/Benchmarks Provides utility methods for executing and measuring benchmark actions. It requires Stopwatch and Dictionary types. Use this to structure your benchmark tests. ```C# private static void Execute(string name, Dictionary initMap, Dictionary actionMap) { Console.WriteLine("------------- {0} ------------- ", name); Console.WriteLine("*** Initialization"); Measure(Watch, initMap, 1); Console.WriteLine(); foreach (int iterationCount in Iterations) { Console.WriteLine("*** Executing for {0} iterations", iterationCount); Measure(Watch, actionMap, iterationCount); Console.WriteLine(); } Console.WriteLine(); } ``` ```C# private static void Measure(Stopwatch watch, Dictionary actionMap, int iterationCount) { foreach (var entry in actionMap) { watch.Start(); for (int i = 0; i < iterationCount; i++) entry.Value(); watch.Stop(); Console.WriteLine("{0,-35} {1,6} ms", entry.Key + ":", watch.ElapsedMilliseconds); watch.Reset(); } } ``` -------------------------------- ### Type Querying and Formatting Extensions Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Queries Extension methods for identifying framework types and retrieving pretty-printed type names. ```C# bool IsFrameworkType( this Type type ) string Name( this Type type ) ``` -------------------------------- ### Standard Field Access Usage Source: https://github.com/buunguyen/fasterflect/wiki/Standard-Access Demonstrates chaining field setters and retrieving values from types and instances. ```C# Type type = typeof(Person); type.SetFieldValue("staticIntField", 10).SetFieldValue("staticObjField", anObj); int i = (int)type.GetFieldValue("staticIntField"); object person = type.CreateInstance(); person.SetFieldValue("name", "tommy").SetFieldValue("age", 15); string name = (string)person.GetFieldValue("name"); int age = (int)person.GetFieldValue("age"); ``` -------------------------------- ### Invoke a dynamic method via delegate Source: https://github.com/buunguyen/fasterflect/wiki/Accessing Shows how to use the delegate returned by the dynamic method generator. ```C# MethodInvoker invoker = CreateDelegate(personType, "GetName"); string name = (string)invoker.Invoke(personObject); ``` -------------------------------- ### Caching Delegates with Fasterflect Source: https://github.com/buunguyen/fasterflect/blob/master/README.md Shows how to cache delegates for field getters, constructor invocation, property setters/getters, method calls, and property mapping for improved performance. ```csharp var range = Enumerable.Range(0, 10).ToList(); // Let's cache the getter for InstanceCount StaticMemberGetter count = type.DelegateForGetStaticFieldValue("InstanceCount"); // Now cache the 2-arg constructor of Person and playaround with the delegate returned int currentInstanceCount = (int)count(); ConstructorInvoker ctor = type.DelegateForCreateInstance(new[] { typeof(int), typeof(string) }); range.ForEach(i => { object obj = ctor(i, "_" + i); AssertTrue(++currentInstanceCount == (int)count()); AssertTrue(i == (int)obj.GetFieldValue("id")); AssertTrue("_" + i == obj.GetPropertyValue("Name").ToString()); }); // Getter/setter MemberSetter nameSetter = type.DelegateForSetPropertyValue("Name"); MemberGetter nameGetter = type.DelegateForGetPropertyValue("Name"); object person = ctor(1, "John"); AssertTrue("John" == (string)nameGetter(person)); nameSetter(person, "Jane"); AssertTrue("Jane" == (string)nameGetter(person)); // Invoke method person = type.CreateInstance(); MethodInvoker walk = type.DelegateForCallMethod("Walk", new[] { typeof(int) }); range.ForEach(i => walk(person, i)); AssertTrue(range.Sum() == (int)person.GetFieldValue("milesTraveled")); // Map properties var ano = new { Id = 4, Name = "Doe" }; var mapper = ano.GetType().DelegateForMap( type ); mapper(ano, person); AssertTrue(4 == (int)person.GetPropertyValue("Id")); AssertTrue("Doe" == (string)person.GetPropertyValue("Name")); ```