Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Prefix" and "as" cast

This seems to be a very stupid question about casting, but...

I have the following setup:

There are a number of classes derivces from a main class. At some point in time and space I get an item, and want to handle it as object of subclass.

Asume:

class subClassA : mainclass 
class subClassB : mainclass 

Now I have some if to ask which class it is:

if(someObject is subClassA)
{
    subClassA aA = someObject as subClassA ;
}

While for most subClasses the correct object is returned, I get for one subClass a null-Object.

If I do the following:

if(someObject is subClassA)
{
    subClassA aA = someObject as subClassA ; // <- aA = null; someObject is shown in debugger as object of subClassA

    object test = someObject as subClassA; // <- object is not null
    // or 
    subClassA aB = (subClassA)someObject; // <- object is not null, shows the correct object
}

I have results in test and aB.

What I do not understand:

Why does as fail and the prefix cast succeed?


Now I'm completly lost.

if(someObject is subClassA)
{
    subClassA aA = someObject as subClassA ; // <- aA = null; someObject is shown in debugger as object of subClassA

    subClassA aB = someObject as subClassA ; // <- aB != null.
}

if(someObject is subClassA)
{
    subClassA aB = someObject as subClassA ; // <- aB != null.
}

The name aA is localy defined. Only one thread accesses the method. If I just rename aA it works.

like image 342
Offler Avatar asked Jan 31 '13 16:01

Offler


1 Answers

The scenario you are describing is confusing to say the least so could you try the following:

subClassA aA = (someObject as subClassA) ?? (subClassA)someObject;

Does that work (eg aA not null)?

You might want to refer to the following post for some details on as:

Casting vs using the 'as' keyword in the CLR

Still investigating some more but I am not sure how to recreate the scenario...

EDIT:

Reading a lot from some very smart people (Skeet and Lippert) trying to find the answer...

See is documenation:

http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.110).aspx

as / conversion documentation:

http://msdn.microsoft.com/en-us/library/ms173105.aspx

like image 132
Kelsey Avatar answered Oct 05 '22 06:10

Kelsey