Tutorial :How to avoid a NullReferenceException


 if (alMethSign[z].ToString().Contains(aClass.Namespace))  

Here, I load an exe or dll and check its namespace. In some dlls, there is no namespace, so aclass.namespace is not present and it's throwing a NullReferenceException.

I have to just avoid it and it should continue with rest of the code. If I use try-catch, it executes the catch part; I want it to continue with the rest of the code.


Is aClass a Type instance? If so - just check it for null:

if (aClass != null && alMethSign[z].ToString().Contains(aClass.Namespace))  


Don't catch the exception. Instead, defend against it:

string nmspace = aClass.Namespace;    if (nmspace != null && alMethSign[z].ToString().Contains(nmspace))  {      ...  }  


Add the test for null in the if statement.

if(aClass.NameSpace != null && alMethSign[z].ToString().Contains(aClass.Namespace))  


Or use an extension method to that checks for any nulls and either returns an empty string or the string value of the object:

public static string ToSafeString(this object o)  {  return o == null ? string.Empty : o.ToString();    }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »