How do I find the return type of a method with System.Reflection.MethodBase in C#?
Asked Answered
G

4

29

how do I find out the return type of a method from the MethodBase? I'm using PostSharp and trying to override the CompileTimeValidate(MethodBase method) method to make sure the attribute is applied to a method with the correct signature.

Thanks,

Goode answered 22/3, 2010 at 18:25 Comment(0)
P
23

MethodBase is used as a base class of MethodInfo which has a property ReturnType.

You could try and cast to an instance of MethodInfo and check that property.

Porty answered 22/3, 2010 at 18:29 Comment(1)
What if we want to find it from MemberInfo. Assume this scenario that we want to filter all the members, like methods and fields that are/returning string type. Does MemberInfo has any property to indicate that?Rory
M
23

MethodBase itself does not have a return type because in addition to normal methods it also is used to represent methods, such as constructors, which have no return type. Instead you need to see if it's an instance of MethodInfo and check that for the ReturnType property.

CompileTimeValidate(MethodBase method) {
  var normalMethod = method as MethodInfo;
  if( normalMethod != null) {
    ValidateReturnType(normalMethod.ReturnType);
  }
}
Multifoil answered 22/3, 2010 at 18:30 Comment(0)
P
2

Try something like this. MethodInfo has the property but MethodBase is used for constructors as well, and they do not have a return type.

MethodBase b = this.GetType().GetMethods().First(); 
if(b is MethodInfo)
    MessageBox.Show((b as MethodInfo).ReturnType.Name);
Pacien answered 22/3, 2010 at 18:31 Comment(2)
Minor point...if you're already checking b is MethodInfo, then a direct cast (MethodInfo)b is slightly preferable to b as MethodInfo.Moralize
The guideline I follow: Use as when receiving a null (for an incompatible type) is acceptable to your code. In this case, since a null is not acceptable inside the if, use (MethodInfo)b instead. Better yet, avoid the cost of doing the cast twice by using as instead of is and testing against null.Posse
P
0

Try the MethodInfo.ReturnType property.

To get the return type property, first get the Type. From the Type, get the MethodInfo. From the MethodInfo, get the ReturnType.

It seems like you can't do it with MethodBase...

http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.returntype.aspx

Perilune answered 22/3, 2010 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.