I have a piece of code that feels like this:(I’ve stripped the methods out because they don’t help for this question)
public abstract class A { }
public interface I { }
public class C : A , I { }
public class Program
{
static void Update<T>(List<T> l,A a,I i,C c)
{
l.Add((T)a);//Error
l.Add((T)i);
l.Add((T)c);//Error
}
}
The casting fails at compile time for the abstract and the concrete class, but not the interface.
I know I could do something like l.Add((T)(object)a); to trick the compiler, but I don’t understand why casting the interface to T works.(if they all went wrong then I could assume its some kind of type-check error)
I tried it in java, and they all work.
public static <T> void update(List<T> l,C c,I i,A a){
l.add((T)c);//ok
l.add((T)i);//ok
l.add((T)a);//ok
}
Is it just because the way c# compiler is, or I am missing some concept on OOP?
To make the compiler understand your code, you must constrain the
Twith keywordwhere, like this:This is because
Tcan be everything by default, even not class, and only after constrains all variants of the code will work.You can compile this only if you constrain your method like I mention it, so the only use you can do is:
This is useless, and you should rewrite your code. I think, you should use more interfaces, and less base classes.