Note that there are some explanatory texts on larger screens.

plurals
  1. POInvalidCastException on Generics
    primarykey
    data
    text
    <p>Coming from the Java world, programming with generics and C# is often a headache. Like this one:</p> <pre><code>interface ISomeObject { } class SomeObjectA : ISomeObject { } class SomeObjectB : ISomeObject { } interface ISomething&lt;T&gt; where T : ISomeObject { T GetObject(); } class SomethingA : ISomething&lt;SomeObjectA&gt; { public SomeObjectA GetObject() { return new SomeObjectA(); } } class SomethingB : ISomething&lt;SomeObjectB&gt; { public SomeObjectB GetObject() { return new SomeObjectB(); } } class SomeContainer { private ISomething&lt;ISomeObject&gt; Something; public void SetSomething&lt;T&gt;(ISomething&lt;T&gt; s) where T : ISomeObject { Something = (ISomething&lt;ISomeObject&gt;)s; } } class TestContainerSomething { static public void Test() { SomeContainer Container = new SomeContainer(); Container.SetSomething&lt;SomeObjectA&gt;(new SomethingA()); } } </code></pre> <p>Which results into an <code>InvalidCastException</code> at <code>Something = (ISomething&lt;ISomeObject&gt;)s;</code>. In Java, this would work, and I could even use (if all else fails) the generics wildcard <code>&lt;?&gt;</code>. This is not possible in C#. </p> <p>While this is just an example that I put together to explain the problematic, how can this exception be eliminated? The only main constraint is that <code>SomeContainer</code> <strong>cannot</strong> be a generic class</p> <p>** <strong>Note</strong> ** : there are many questions about this, but none of them (that I could find) address a generic class member inside a non generic class.</p> <p>** <strong>Update</strong> **</p> <p>Inside the method <code>SetSomething</code>, I added these lines :</p> <pre><code>Console.WriteLine(s.GetType().IsSubclassOf(typeof(ISomething&lt;SomeObjectA&gt;))); Console.WriteLine(s.GetType().ToString() + " : " + s.GetType().BaseType.ToString()); foreach (var i in s.GetType().GetInterfaces()) { Console.WriteLine(i.ToString()); } </code></pre> <p>which to my surprise output</p> <pre><code>False SomeThingA : System.Object ISomething`1[SomeObjectA] </code></pre> <p>Is this why I get this exception?</p>
    singulars
    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.
    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