I'm looking for a way to filter out methods which have the unsafe
modifier via reflection. It doesn't seem to be a method attribute.
Is there a way?
EDIT: it seems that this info is not in the metadata, at least I can't see it in the IL. However reflector shows the unsafe
modifier in C# view. Any ideas on how it's done?
EDIT 2: For my needs I ended up with a check, that assumes that if one of the method's parameters is a pointer, or a return type is a pointer, then the method is unsafe.
public static bool IsUnsafe(this MethodInfo methodInfo)
{
if (HasUnsafeParameters(methodInfo))
{
return true;
}
return methodInfo.ReturnType.IsPointer;
}
private static bool HasUnsafeParameters(MethodBase methodBase)
{
var parameters = methodBase.GetParameters();
bool hasUnsafe = parameters.Any(p => p.ParameterType.IsPointer);
return hasUnsafe;
}
This doesn't handle, of course, a situation where an unsafe block is executed within a method, but again, all I am interested in is the method signature.
Thanks!
Unfortunately the unsafe keyword simply wraps the body of the method in an unsafe block and doesn't emit anything that reflection would see. The only way to be certain is to disassemble the method and see if there are any unsafe operations inside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With