Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# GetMethod vs GetRuntimeMethod

Tags:

c#

reflection

I am using GetRuntimeMethod to get a method out of type. Everything works fine but I have noticed that there is a GetMethod. What is the difference between the two?

this.target.GetType().GetRuntimeMethod(
    "MethodName",
    new System.Type[0]
)?.Invoke(targetObject, null);

From the names I can only guess that GetRuntimeMethod works while the program is running. And GetMethod works during program compilation?

Are there any advantages of using one instead of another? (This last question can be deductible from the answer to what is the difference between the two of course)

like image 275
Candid Moon _Max_ Avatar asked Apr 08 '26 21:04

Candid Moon _Max_


1 Answers

GetMethod works on System.Type, the abstract base class for RuntimeType. GetRuntimeMethod calls GetMethod after validating the type is actually a RuntimeType (and not a (possibly user defined) child of Type), so it is slower than GetMethod. GetRuntimeMethod throws an exception if not passed a class derived from RuntimeType.

From the documentation for Type:

Type is an abstract base class that allows multiple implementations. The system will always provide the derived class RuntimeType. In reflection, all classes beginning with the word Runtime are created only once per object in the system and support comparison operations.

Also this article has further details on extending Type and when you might need a RuntimeType specifically.

like image 88
NetMage Avatar answered Apr 10 '26 14:04

NetMage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!