why static methods will not throw NullReferenceException?
Why static methods will not throw NullReferenceException? or will it throw NullReferenceException? If it will not throw the error, can anyone explain why with relevant example.开发者_如何学运维
Static methods don't relate to an instance of the type, so there's no reference to potentially be null.
Of course, if the body of a static method does something which will normally throw an exception, it will be propagated as usual:
class Test
{
static void Main()
{
GoBang();
}
static void GoBang()
{
string s = null;
int y = s.Length; // Bang! NullReferenceException
}
}
Static method are called with class which is never null
. Instance methods are called with instance which can be null
as the programmer did not do new
on it.
The CLR considers any type to be unstable if it throws an unhandled exception (of any kind) in a type constructor. Attempting to access any member of the unstable type will cause a TypeInitializationException to be thrown.
So, NullReferenceException will be thrown but is marshalled into the TypeInitializationException by the runtime.
精彩评论