Domanda

After some testing which is about "null dereference", below code can "dereference a null pointer, thereby raising a NullException".

if((validateControl as WebControl) != null)
    (validateControl as WebControl).CssClass (IsValid) ? "stack" : "overflow";

Can (validateControl as WebControl).CssClass be null with above using?

The result is seen in document which is produced by Fortify.

È stato utile?

Soluzione

To get false when it's not a WebControl, and true otherwise:

bool isWebControl = validateControl is WebControl;

To get null when it's not a WebControl, and a WebControl otherwise:

WebControl webControl = validateControl as WebControl;

Can (validateControl as WebControl) be null?

Yes, every time you use as, the result could be null in theory. Code analysis tools don't see that you just checked that it is not null, and will still assume the next use of as is possibly null. So you should put it in a variable and use that instead:

WebControl webControl = validateControl as WebControl;
if (webControl != null)
{
    // Here 'webControl' is surely _not_ null.
    webControl.CssClass = Page.IsValid ? "stack" : "overflow";
}

Can (validateControl as WebControl).CssClass be null?

The value you get from CssClass might be null. But since CssClass is a property, the property will always be there as long as validateControl is a WebControl.

Altri suggerimenti

How about reformatting your code to be more explicit.

var webControl = validateControl as WebControl;
if(webControl != null)
{
    var cssClass = IsValid ? "stack" : "overflow";
    webControl.CssClass = cssClass;
}

Yes it could. If it matters, once you know validateControl is not null and is a WebControl, then you test CssClass for nullability and possibly empty or just whitespace depending on what "valid" means

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top