Why are arrays covariant but generics are invariant?

Via wikipedia: Early versions of Java and C# did not include generics (a.k.a. parametric polymorphism). In such a setting, making arrays invariant rules out useful polymorphic programs. For example, consider writing a function to shuffle an array, or a function that tests two arrays for equality using the Object.equals method on the elements. The implementation … Read more

Convert generic List/Enumerable to DataTable?

Here’s a nice 2013 update using FastMember from NuGet: IEnumerable<SomeType> data = … DataTable table = new DataTable(); using(var reader = ObjectReader.Create(data)) { table.Load(reader); } This uses FastMember’s meta-programming API for maximum performance. If you want to restrict it to particular members (or enforce the order), then you can do that too: IEnumerable<SomeType> data = … Read more

What causes javac to issue the “uses unchecked or unsafe operations” warning

This comes up in Java 5 and later if you’re using collections without type specifiers (e.g., Arraylist() instead of ArrayList<String>()). It means that the compiler can’t check that you’re using the collection in a type-safe way, using generics. To get rid of the warning, just be specific about what type of objects you’re storing in … Read more

Create Generic method constraining T to an Enum

Since Enum Type implements IConvertible interface, a better implementation should be something like this: public T GetEnumFromString<T>(string value) where T : struct, IConvertible { if (!typeof(T).IsEnum) { throw new ArgumentException(“T must be an enumerated type”); } //… } This will still permit passing of value types implementing IConvertible. The chances are rare though.

Pass An Instantiated System.Type as a Type Parameter for a Generic Class

You can’t do this without reflection. However, you can do it with reflection. Here’s a complete example: using System; using System.Reflection; public class Generic<T> { public Generic() { Console.WriteLine(“T={0}”, typeof(T)); } } class Test { static void Main() { string typeName = “System.String”; Type typeArgument = Type.GetType(typeName); Type genericClass = typeof(Generic<>); // MakeGenericType is badly … Read more

Why don’t Java Generics support primitive types?

Generics in Java are an entirely compile-time construct – the compiler turns all generic uses into casts to the right type. This is to maintain backwards compatibility with previous JVM runtimes. This: List<ClassA> list = new ArrayList<ClassA>(); list.add(new ClassA()); ClassA a = list.get(0); gets turned into (roughly): List list = new ArrayList(); list.add(new ClassA()); ClassA … Read more