How to call a static method using reflection in C#
By FoxLearn 3/4/2025 9:45:33 AM 142
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
Freedash bootstrap lite
11/13/2024
RuangAdmin Template
11/17/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
Horizon MUI Admin Dashboard Template
11/18/2024