Generics: reified and erased (C# and Java)
A generic type is a type with a hole in it. C# and Java fill the hole in different places: C# at run time, so List<int> and List<string> are two different types and the runtime knows which is which; Java at compile time only, so both are one class and the type argument is gone after the compiler has checked it. This page writes the same task twice and then asks each runtime what it knows.
The task in C#
Two lists of different type arguments, their runtime types, and a generic method with a constraint. The last two lines ask the two lists for their types and compare them:
Console.WriteLine("generics 1.0");
var ints = new List<int> { 1, 2, 3 };
var texts = new List<string> { "a", "ccc", "bb" };
Console.WriteLine($"int list type {ints.GetType()}");
Console.WriteLine($"string list type {texts.GetType()}");
Console.WriteLine($"same type {ints.GetType() == texts.GetType()}");
Console.WriteLine($"sum {Sum(ints)}");
Console.WriteLine($"longest {Longest(texts)}");
static int Sum(List<int> values)
{
var total = 0;
foreach (var value in values)
{
total += value;
}
return total;
}
static T Longest<T>(List<T> values) where T : IComparable<T>
{
var best = values[0];
foreach (var value in values)
{
if (value.CompareTo(best) > 0)
{
best = value;
}
}
return best;
}
dotnet run
echo "status: $?"
generics 1.0
int list type System.Collections.Generic.List`1[System.Int32]
string list type System.Collections.Generic.List`1[System.String]
same type False
sum 6
longest ccc
status: 0
The same task in Java
The same lists and the same generic method, and then the part Java allows and C# does not: a raw List without a type argument, which the compiler accepts with a warning, into which a string goes, and a cast that fails at run time:
import java.util.ArrayList;
import java.util.List;
public class Generics {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>(List.of(1, 2, 3));
List<String> texts = new ArrayList<>(List.of("a", "ccc", "bb"));
System.out.println("generics 1.0");
System.out.println("int list type " + ints.getClass().getName());
System.out.println("string list type " + texts.getClass().getName());
System.out.println("same type " + (ints.getClass() == texts.getClass()));
System.out.println("sum " + sum(ints));
System.out.println("longest " + longest(texts));
List raw = ints;
raw.add("not a number");
System.out.println("raw size " + raw.size());
try {
int total = 0;
for (Object value : ints) {
total += (Integer) value;
}
System.out.println("total " + total);
} catch (ClassCastException ex) {
System.out.println("runtime " + ex.getClass().getSimpleName());
}
}
static int sum(List<Integer> values) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}
static <T extends Comparable<T>> T longest(List<T> values) {
T best = values.get(0);
for (T value : values) {
if (value.compareTo(best) > 0) {
best = value;
}
}
return best;
}
}
javac -g -d out Generics.java
java -cp out Generics
echo "status: $?"
generics 1.0
int list type java.util.ArrayList
string list type java.util.ArrayList
same type true
sum 6
longest ccc
raw size 4
runtime ClassCastException
status: 0
What differs
- The two list types are different in C#: List`1[System.Int32] against List`1[System.String]. In Java both are java.util.ArrayList and the comparison is true, because the type argument is erased.
- Erasure is why Java can put a string into a list of integers through a raw type, and why the failure is a ClassCastException at run time instead of a compile error. C# has no raw type to open that door: the cast of a list to another type argument is refused by the compiler or fails at the cast, not at the element.
- The generic method is the same idea in both, and the constraint is spelled differently: where T : IComparable<T> against <T extends Comparable<T>>.
- A Java list of int is a list of Integer: the type argument cannot be a primitive, so every element is boxed. A C# List<int> stores the integers themselves, which is one difference the next pages measure.
- The raw-type warning of javac, uses unchecked or unsafe operations, is the compiler saying that it cannot check what the erased type promised.
The next page is about the members a class exposes: a C# property is a member with accessors, and a Java field is private with a method in front of it.
Exercises
- Print the type of an array of each type argument in both languages.
- Add a second constraint to the generic method and see which compiler demands it at the call.
- In Java, put the raw list behind a method that takes a List<Integer> and read the exception it throws.
- Explain why new T() compiles in neither language and what each one offers instead.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Where does C# keep the type argument of a generic type?
Answer
At run time, so List<int> and List<string> are two types
The measured types differ and the comparison is False.
-
What does erasure do in Java?
Answer
It removes the type argument after compilation, so both lists are one class
Both measured types are java.util.ArrayList and the comparison is true.
-
What does this program print?
var values = new List<int> { 1, 2, 3 }; Console.WriteLine(values.Sum());Answer
6
The sum of the C# list is the measured line sum 6.
-
What does a raw List allow in Java?
Answer
Adding an element of any type, checked only by a cast later
The page adds a string and gets a ClassCastException when reading.
-
What does this program print?
var ints = new List<int> { 1 }; var texts = new List<string> { "a" }; Console.WriteLine(ints.GetType() == texts.GetType());Answer
False
The two C# list types are different, which is the measured comparison of the page.
-
Which primitive type can a Java type argument be?
Answer
None: the argument is a wrapper such as Integer
Java generics work on reference types, so every element is boxed.
-
What does this program print?
var words = new List<string> { "a", "ccc", "bb" }; Console.WriteLine(words.OrderBy(w => w.Length).Last());Answer
ccc
The longest string of the list is the measured answer of both programs.
-
What does the javac note about unchecked operations mean?
Answer
The compiler cannot check what the erased type promised
The page shows the note next to the raw list that caused it.
-
Why is the C# generic method constraint written with IComparable?
Answer
So the method can call CompareTo on T
The constraint is what allows the comparison inside the method.
-
What does this program print?
Console.WriteLine(typeof(int));Answer
System.Int32
The runtime name of a type argument is the full type name.
The C# program was built with the .NET SDK 10.0.303 and the Java program with OpenJDK 21.0.13.1 (javac 21.0.13.1), both run on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.
Article author: Arthur Isaev