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
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
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 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