kala-tamin How to avoid a NullReferenceException

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.

Unable to catch exception


Exception or Error Code Enum
Is aClass a Type instance? If so - just check it for null:.
Passing Exception Types down through a menu
if (aClass != null && alMethSign[z].ToString().Contains(aClass.Namespace)) 

Throw a custom exception from a service to an activity

HTTPS hostname wrong: should be <sub.domain.com>. What causes this?


Should I use an exception in this case?
Don't catch the exception.

If i dont catch exception on Server side in WCF, will it crash the server side app?
Instead, defend against it:.
When is best to use exceptions in PHP?
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();  } 

91 out of 100 based on 71 user ratings 421 reviews