Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Reflection, Attributes and Metadata

MethodInfo and PropertyInfo

Reference for MethodInfo, PropertyInfo and FieldInfo in C#: find members by name, call methods with Invoke, read and write properties, and handle exceptions.

MethodInfo, PropertyInfo and FieldInfo describe the members of a type at run time. You get them from a Type (GetMethod, GetProperty, GetField) and then use them to call a method, read a value or write a value on an instance, without the compiler knowing the member at build time.

This is what serializers, object mappers and test frameworks do: they receive an object they have never seen, discover its properties, and read or set them by name. The price is speed (each call is slower than a direct call) and safety (mistakes appear at run time, not compile time).

C#
PropertyInfo p = typeof(Person).GetProperty("Name")!;
p.SetValue(person, "Ada");
object? value = p.GetValue(person);

Try it

C# Reading, writing and invoking

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Exceptions, overloads and parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public abstract class MethodInfo : MethodBase
{
    public object? Invoke(object? obj, object?[]? parameters);
    public MethodInfo MakeGenericMethod(params Type[] typeArguments);
    public Type ReturnType { get; }
    public ParameterInfo[] GetParameters();
}

public abstract class PropertyInfo : MemberInfo
{
    public object? GetValue(object? obj);
    public void SetValue(object? obj, object? value);
    public bool CanRead { get; }  public bool CanWrite { get; }
    public Type PropertyType { get; }
}
Member Description
Invoke(obj, args) Calls the method. Pass null for obj when the method is static. args is null or empty for no arguments.
GetValue(obj) / SetValue(obj, value) Read or write a property (or a field with FieldInfo). Indexers take an extra index array.
GetGetMethod() / GetSetMethod() The accessor methods; null when absent or not public.
CreateDelegate<T>() Turns the method into a delegate for fast repeated calls.
GetParameters() Parameter names, types and defaults.
IsStatic, IsPublic, IsVirtual, IsGenericMethod Flags describing the method.

Returns: Invoke returns the method's result boxed as object, or null for void methods.

Errors: TargetInvocationException wraps any exception thrown by the invoked method (look at InnerException). ArgumentException is thrown when argument types or counts do not match. TargetException (or NullReferenceException) occurs when an instance method is invoked on null. AmbiguousMatchException comes from looking up an overloaded name without parameter types. ArgumentException is also thrown when you call SetValue on a read-only property.

Usage notes

  • Visibility depends on the flags used for the lookup, not on the call. A member found with NonPublic can be invoked even though it is private. Calling private code this way breaks encapsulation, so keep it to tests and tools.
  • Wrapped exceptions: unwrap TargetInvocationException.InnerException before reporting. Delegates created with CreateDelegate do not wrap.
  • Boxing and allocation: arguments and results are boxed, and Invoke allocates an array each time. For hot paths, create a typed delegate once with CreateDelegate<Func<...>>() or use a compiled expression tree.
  • Overloads: give GetMethod the parameter types to pick one exactly ([typeof(int), typeof(int)]).
  • Generic methods must be closed with MakeGenericMethod before Invoke.
  • Properties are methods: get_Name and set_Name exist as special-name methods; GetMethods() includes them, so filter on IsSpecialName.
  • ref/out parameters: the args array is updated in place, so read the value back from the array after the call.
  • Auto-property backing fields have unspeakable names (<Owner>k__BackingField); use the property instead.
  • Trimming: members only reached by reflection can be removed by the trimmer; annotate with DynamicallyAccessedMembers or avoid reflection.