astro boy astro boy - 1 year ago 33
C# Question

IS operator and where an object is coming from

I have the following class written by someone else that I'm trying to understand (I omitted the code that is not necessary for this example):

public abstract class UserControl : System.Web.UI.UserControl
{
...

public virtual bool IsAadmin(TheUser theUser)
{
if (Page is Page)
return ((Page)Page).IsAadmin(theUser);

return false;
}
...


Edit: (note: in stackoverflow the first
Page
in the
if
statement is highlighted blue but in visual studio it isn't)


In the
if
statement intellisense shows that the first Page is of type
System.Web.UI.Page Control.Page
and the second
Page
is from
Something.Products.Web.Page
. When I debug through the code, it doesn't seem to go into this
if
statement, so I'm wondering what this code is trying to do? But more importantly where is that first
Page
in the
if
statement is coming from (initialized)? I'm using
Resharper
and it suggest replacing the
if
statement with

var page = Page as Page;
if (page != null)


This change shows that page is null when debugging through it.

Answer Source

The "first page" is actually a Page property of UserControl class your abstract UserControl inherits from. It's of type System.Web.UI.Page and, as per documentation, returns

a reference to the Page instance that contains the server control.

The is keyword evaluates to true when

the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

It seems that when you were debugging your code, the examined UserControl was not contained in a page of type Something.Products.Web.Page.

Regarding the Resharper suggestion: in your original code, you are effectively casting the Page property twice - first, when using is keyword and second when casting it explicitly. With the code generated by Resharper, the cast only occurs once. When the if statement evaluates to true, you can be sure that the page variable holds a reference to the Something.Products.Web.Page and do not have to cast it again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download