Avoid reflection in Hot Paths

In this section you can read about reflection and when it should be avoided.


Reflection allows to dynamically create an instance of a type, or get the type from an existing object and invoke its methods or access its fields and properties.

Reflection is very powerful but expensive.

Use reflection only when necessary, for example, when creating a COM object.


Avoid using it in performance-sensitive scenarios and hot paths. In these cases, try to use strong types and call the methods directly.

This method invokes the MyMethod method of the object myObject using reflection.

public string MyMethod(object myObject)
    return myObject.GetType().GetMethod("MyMethod").

In this case, the type MyClass is known so it replaces the object and the MyMethod method can be called directly.

public string MyMethod(MyClass myObject)
    return myObject.MyMethod();

Last updated