views:

413

answers:

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

+9  A: 

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

string nmspace = aClass.Namespace;

if (nmspace != null && alMethSign[z].ToString().Contains(nmspace))
{
    ...
}
Jon Skeet
+1  A: 

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

if (aClass != null && alMethSign[z].ToString().Contains(aClass.Namespace))
Marc Gravell
+4  A: 

Add the test for null in the if statement.

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

i'm using extension methods for this frequent constructions.

for example:

namespace System { public static bool IsNotEmpty(this string text) { return !string.IsNullOrEmpty(text); } }

and for object:

 public static bool IsNotNull(this object instance)
    {
        return instance != null;
    }

using this is more readable (at least for me :-) ):

bool isnotnull = aClass.IsNotNull() && aClass.Namespace.IsNotEmpty() && alMethSign[z].IsNotNull();

if(isnotnull && alMethSign[z].ToString().Contains(aclass.namespace))..
Jan Remunda
A: 

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

}