How to call a static method using reflection in C#
By Tan Lee Published on Mar 04, 2025 200
To call a static method using reflection in C#, follow these steps:
- Get the
Type
of the class. - Retrieve the
MethodInfo
of the static method usingGetMethod()
. - Invoke the method using
MethodInfo.Invoke()
.
Reflection allows you to access properties and methods dynamically at runtime. Below is an example of invoking a static method using reflection:
MethodInfo methodInfo = typeof(Type).GetMethod(StaticMethodName, BindingFlags.Static | BindingFlags.Public); var result = (ReturnType)methodInfo.Invoke(null, null);
Note: The above example calls a parameterless static method. If the method requires parameters, pass them as arguments like this:
methodInfo.Invoke(null, new object[] { param1, param2 });
For example:
using System; using System.Reflection; class Example { public static void Greet(string name) { Console.WriteLine($"Hello, {name}!"); } } class Program { static void Main() { // Get the Type of the class Type type = typeof(Example); // Get MethodInfo for the static method MethodInfo methodInfo = type.GetMethod("Greet", BindingFlags.Static | BindingFlags.Public); // Invoke the static method with a parameter methodInfo.Invoke(null, new object[] { "Alice" }); } }
In this example:
typeof(Example)
: Gets the type of the class.GetMethod("Greet", BindingFlags.Static | BindingFlags.Public)
: Retrieves the static method.Invoke(null, new object[] { "Alice" })
: Calls the method, passing"Alice"
as an argument.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization
Categories
Popular Posts
Horizon MUI Admin Dashboard Template
Nov 18, 2024
Elegent Material UI React Admin Dashboard Template
Nov 19, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024
Material Lite Admin Template
Nov 14, 2024