Possible NullReferenceException?

My editor warns me that a line might throw on occasions, the relevant lines are:

var sf = new StackFrame(1, true);

line = sf.GetFileLineNumber();
file = sf.GetMethod().DeclaringType.ToString();

The warning: Possible System.NullReferenceException.
It underlines this specific part:
sf.GetMethod().DeclaringType

How could it throw null? Don’t you always need a method to invoke the caller, and if you have the method, isn’t DeclaringType it’s name? Do methods without name exist?

Adding nullable token ? after DeclaringType makes the warning go away, but I’m still wondering how it could be null.

Your message looks like it’s coming from a static analyzer. It’s not possible for a static analysis to determine GetMethod() won’t return null because it depends on the runtime context.

It might be true that this method will never return null in a practical situation, but asking the static analyzer to know this is similar to asking the compiler to know what data is in a user file. It’s not possible until the program is run.

In this case, the static analyzer is just being cautious, which is why it says “possible”

1 Like