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