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.
  • 113,939
  • 20
  • 158
  • 187
Arunachalam
  • 5,417
  • 20
  • 52
  • 80
  • 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,421,763
  • 867
  • 9,128
  • 9,194
4

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

if (aClass != null && alMethSign[z].ToString().Contains(aClass.Namespace))
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4

Add the test for null in the if statement.

if(aClass.NameSpace != null && alMethSign[z].ToString().Contains(aClass.Namespace))
Megacan
  • 2,510
  • 3
  • 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();

}