How to avoid a NullReferenceException

萝らか妹 提交于 2019-12-06 15:52:11

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

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

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!