Note that there are some explanatory texts on larger screens.

plurals
  1. PO"Prefix" and "as" cast
    text
    copied!<p>This seems to be a very stupid question about casting, but...</p> <p>I have the following setup:</p> <p>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.</p> <p>Asume:</p> <pre><code>class subClassA : mainclass class subClassB : mainclass </code></pre> <p>Now I have some if to ask which class it is:</p> <pre><code>if(someObject is subClassA) { subClassA aA = someObject as subClassA ; } </code></pre> <p>While for most subClasses the correct object is returned, I get for one subClass a <code>null</code>-Object.</p> <p>If I do the following:</p> <pre><code>if(someObject is subClassA) { subClassA aA = someObject as subClassA ; // &lt;- aA = null; someObject is shown in debugger as object of subClassA object test = someObject as subClassA; // &lt;- object is not null // or subClassA aB = (subClassA)someObject; // &lt;- object is not null, shows the correct object } </code></pre> <p>I have results in <code>test</code> and <code>aB</code>.</p> <p>What I do not understand: </p> <p>Why does <code>as</code> fail and the prefix cast succeed?</p> <hr> <p>Now I'm completly lost. </p> <pre><code>if(someObject is subClassA) { subClassA aA = someObject as subClassA ; // &lt;- aA = null; someObject is shown in debugger as object of subClassA subClassA aB = someObject as subClassA ; // &lt;- aB != null. } if(someObject is subClassA) { subClassA aB = someObject as subClassA ; // &lt;- aB != null. } </code></pre> <p>The name aA is localy defined. Only one thread accesses the method. If I just rename aA it works.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload