Why do I get warning CS8602?

Viewed 4926

I saw many questions regarding this error, but all/most of them contain complex code or types.

I used this line for many years to prompt the name of the method with an error:

string currentMethod = System.Reflection.MethodBase.GetCurrentMethod().Name;

But now I get this error :

warning CS8602: Dereference of a possibly null reference.

What should I change / Is there another way to get the name of the current method without having this error?

Thanks

4 Answers

The problem is quiet clear. The name might be null at some point. Try using ? so the compiler will know that you are aware of a possible null coming from System.Reflection.MethodBase.GetCurrentMethod().Name;

Usage:

string? currentMethod = System.Reflection.MethodBase.GetCurrentMethod().Name;

Documentation: read more here.

While you possibly do have an unhandled null variable or property it can be seen that the CS8602 is prone to false positives. https://github.com/dotnet/roslyn/issues/44805 and https://github.com/dotnet/roslyn/issues/49653

Those are a couple of complex scenarios that people have bothered to report but in my experience even more simple scenarios with very explicit preceding null checks can still result in this warning.

Because efforts to removing this warning can result in you making non-nullable fields nullable just to make the warning go away the solution to CS8602 is often worse than the problem.

The Answer: Downgrade the warning until they fix the false positives.

If you're okay with sometimes get a null back you can do this:

string? currentMethod = System.Reflection.MethodBase.GetCurrentMethod()?.Name;

Note the question mark after the method call.

Related