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
.