Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get warning CS8602?

Tags:

c#

null

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

like image 505
Guy Cohen Avatar asked Mar 04 '26 09:03

Guy Cohen


2 Answers

GetCurrentMethod() is declared to be able to return a null value. If you are sure that the value is not null, you may use the null-forgiving "!" operator e.g.

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

See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving

like image 178
Fried Avatar answered Mar 06 '26 23:03

Fried


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.

like image 23
m12lrpv Avatar answered Mar 06 '26 22:03

m12lrpv



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!