How to avoid a NullReferenceException
-
06-09-2019 - |
Question
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.
Solution
Is aClass
a Type
instance? If so - just check it for null:
if (aClass != null && alMethSign[z].ToString().Contains(aClass.Namespace))
OTHER TIPS
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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow