Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result of "is" expression returns false when run, but true when inspected

Tags:

c#

.net

spring

I have the following code. The CustomControlHelper generates an instance of an object via reflection. At this stage we don't know what type of object we are dealing with. We do know it will be a CustomControl, but we don't know if it implements any particular interface or if it extends any other classes. The following code is trying to establish whether the loaded control implements the IRichAdminCustomControl interface.

Object obj = CustomControlHelper.GetControl(cc.Id, cc.ControlClass);            
if(obj != null)
{
    bool isWhatWeWant = (obj is IRichAdminCustomControl);
    return isWhatWeWant;
}

That's all fine, but I've noticed that when I know I have an object that implements IRichAdminCustomControl, the expression evaluates to false.

Okay, this is where it gets really weird. If I inspect the code when debugging, the expression evaluates to true, but then if I immediately let the code run and inspect the result, it evaluates to false (I've attached an animated gif below to illustrate).

enter image description here

Has anyone come across weirdness like this before and if so, what on earth is causing it?

Incidentally, I believe the product I'm using uses Spring.NET to provide dependency injection in the CustomControlHelper.

like image 454
Iain Fraser Avatar asked Jan 14 '14 03:01

Iain Fraser


1 Answers

If you are using Visual Studio 2010 SP1, I came across this bug:

Misreporting of variable values when debugging x64 code

There is a workaround on that page, posted by Microsoft:

You can either set all projects to compile to x86, or create an intermediate initialised variable declaration to ensure the debugger reports the correct value of the variable being examined.

Try this as a workaround:

bool isWhatWeWant = true;
isWhatWeWant &= (obj is IRichAdminCustomControl);
bool finalValue = isWhatWeWant; // this line should fix isWhatWeWant too in the debugger
return finalValue;

EDIT: seems like VS2012 also encounters similar problems in specific conditions.

like image 75
Cosmin Vană Avatar answered Oct 04 '22 06:10

Cosmin Vană