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

lc.
  • 109,978
  • 20
  • 153
  • 183
Arunachalam
  • 4,657
  • 20
  • 49
  • 78
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Apr 04 '14 at 17:31

4 Answers4

13

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

string nmspace = aClass.Namespace;

if (nmspace != null && alMethSign[z].ToString().Contains(nmspace))
{
    ...
}
Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
4

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

if (aClass != null && alMethSign[z].ToString().Contains(aClass.Namespace))
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
4

Add the test for null in the if statement.

if(aClass.NameSpace != null && alMethSign[z].ToString().Contains(aClass.Namespace))
Megacan
  • 2,472
  • 2
  • 20
  • 31
0

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();

}