Search code examples
visual-studio-2008debuggingimmediate-window

Peculiar behavior of immediate window in VS 2008


Today something peculiar happened while debugging in VS 2008. I will give the small code snippet

List<IPageHandler> myPageList = TaskSOM.PageList;

if( myPageList != null && myPageList.Count > 0 )
{
     PageHandler aPage = myPageList[0] as PageHandler;
     ...; // Some more code below  
}

While running the application the typecast failed and aPage became null (That was the reason for debugging). So all the code that was using that vaiable failed. But during debug the first element in the myPageList was in deed a PageHandler. When I execute the line in immediate window

  PageHandler aPage = myPageList[0] as PageHandler;

aPage variable has proper value. But If move the debugger to that line and execute I get a null. Due to confidentiality I couldn't share the whole code. But has anyone faced such an issue with the immediate window in the past. Is there any material regarding how the immediate window works.


Solution

  • This would be a very good example of code where you don't want to use the as operator. Clearly you cannot afford the cast to fail or you would have included a null test and did something meaningful if the cast failed.

    Use a real cast. You'll get an informative exception that gives you a much better hint why the cast failed:

     PageHandler aPage = (PageHandler)myPageList[0];
    

    Exceptions are your friend, don't avoid them. Taking a wild guess: this could happen when you use a COM object in a thread and the COM server doesn't support marshaling. If that's the case then the exception message will tell you so.