Note that there are some explanatory texts on larger screens.

plurals
  1. POVB typeof operator with generics
    primarykey
    data
    text
    <p>When comparing types in VB the following works as expected and enables the current instance to be compared against a specific inherited class, in this case returning <code>False</code> (snippet from <a href="http://www.linqpad.net/" rel="nofollow">LINQPad</a>)</p> <pre><code>Sub Main Dim a As New MyOtherChildClass a.IsType().Dump() End Sub ' Define other methods and classes here MustInherit class MyBaseClass Public Function IsType() As Boolean Return TypeOf Me Is MyChildClass End Function End Class Class MyChildClass Inherits MyBaseClass End Class Class MyOtherChildClass Inherits MyBaseClass End Class </code></pre> <p>However when generics are introduced the VB compiler fails with the error <code>Expression of type 'UserQuery.MyBaseClass(Of T)' can never be of type 'UserQuery.MyChildClass'.</code></p> <pre><code>' Define other methods and classes here MustInherit class MyBaseClass(Of T) Public Function IsType() As Boolean Return TypeOf Me Is MyChildClass End Function End Class Class MyChildClass Inherits MyBaseClass(Of String) End Class Class MyOtherChildClass Inherits MyBaseClass(Of String) End Class </code></pre> <p>The equivalent code in <strong>C#</strong> compiles and allows the comparison, returning the correct result</p> <pre class="lang-cs prettyprint-override"><code>void Main() { var a = new MyOtherChildClass(); a.IsType().Dump(); } // Define other methods and classes here abstract class MyBaseClass&lt;T&gt; { public bool IsType() { return this is MyChildClass; } } class MyChildClass : MyBaseClass&lt;string&gt; { } class MyOtherChildClass : MyBaseClass&lt;string&gt; { } </code></pre> <p>Why does the VB compiler not allow this comparison?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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