# How do Java and C# generics differ from Rust generics?
Source: https://ruststudio.org/community/t/54/how-do-java-and-c-generics-differ-from-rust-generics
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, OpenJDK 17.0.18, .NET SDK 10.0.302, Windows 11
Category: Help and questions | Kind: FAQ | Tags: porting, generics, java | Views: 0

## Short answer
Java erases type arguments after compiling, so List of String and List of Integer are one class at run time. C# keeps them. Rust compiles a separate copy per type, with the real size known, and checks the code against trait bounds when it is written. The three models differ in what you can do with T inside the generic.

## Answer
## Answer
The syntax of generics looks alike in the three languages, so ports tend to carry their habits over. The habits do not all survive, because the implementations differ.

| | Java | C# | Rust |
|---|---|---|---|
| Type argument at run time | Erased | Kept | Replaced by one compiled copy per type |
| `new T()` inside the generic | Not allowed | Allowed with `where T : new()` | Through a trait: `T::default()` with `T: Default` |
| `int` as a type argument | Not allowed; boxed `Integer` is used | Allowed, no boxing | Allowed; any type |
| Constraint | `T extends Comparable<T>` | `where T : IComparable<T>` | `T: PartialOrd` |
| What is checked, and when | Body checked once against bounds | Body checked once against constraints | Body checked once against bounds |
| Size of a value of type `T` | Always a reference | Value types have their own size | Known per copy: `size_of::<T>()` |

Java, compiled and run with OpenJDK 17.0.18: both lists have the same class, and a value of the wrong type that sneaks in through a raw type is only caught when it is read.

```java
List<String> s = new ArrayList<>();
List<Integer> i = new ArrayList<>();
System.out.println(s.getClass() == i.getClass());   // true
List raw = s;
raw.add(42);                       // allowed after erasure (warns when compiling)
try { String x = s.get(0); } catch (ClassCastException e) { System.out.println("ClassCastException at the read"); }
```

```text
true
ClassCastException at the read
```

C#, .NET SDK 10.0.302:

```csharp
Console.WriteLine(typeof(List<int>) == typeof(List<string>));
Console.WriteLine(typeof(List<int>));
Console.WriteLine(new List<string>().GetType().GetGenericArguments()[0]);
static T Make<T>() where T : new() => new T();
Console.WriteLine(Make<int>());
```

```text
False
System.Collections.Generic.List`1[System.Int32]
System.String
0
```

Rust, rustc 1.93.0. The generic function knows the real type, including its size, and "construct a T" goes through a trait:

```rust title=src/main.rs
use std::any::type_name;
use std::mem::size_of;

fn describe<T>() -> String {
    format!("{} is {} bytes", type_name::<T>(), size_of::<T>())
}

fn main() {
    println!("{}", describe::<Vec<u8>>());
    println!("{}", describe::<(u8, u64)>());
    println!("{}", describe::<Option<u32>>());
    println!("{}", describe::<[u16; 5]>());
    // Rust builds a separate copy of a generic function for each type it is used with:
    // size_of::<T>() inside describe is a constant in each copy.
    let f: fn() -> String = describe::<u8>;
    let g: fn() -> String = describe::<u64>;
    println!("{}", f() != g());
    // no `new T()` and no reflection: construction goes through a trait
    fn make<T: Default>() -> T { T::default() }
    println!("{:?} {:?}", make::<i32>(), make::<String>());
}
```

```text
alloc::vec::Vec<u8> is 24 bytes
(u8, u64) is 16 bytes
core::option::Option<u32> is 8 bytes
[u16; 5] is 10 bytes
true
0 ""
```

Where this matters in a port: Java code that depends on a runtime type check of `T` (`instanceof T` is impossible, but `Class<T>` tokens are passed around) needs an explicit parameter or a trait method in Rust. C# code that uses `typeof(T)` or reflection to choose behaviour should become a trait implemented for each type. Java collections of boxed numbers become `Vec<i32>` and lose the boxing cost and the possibility of `null` elements.

## How to do it
1. For each generic class, write a generic struct or function and list what its body does to `T`. Each operation is a trait bound (see the thread on templates for the table).
2. Replace `new T()`, `T.default` and static abstract members by a trait with an associated function.
3. Replace `instanceof` and casts on `T` by a trait method, or by an `enum` of the possible types.
4. Replace wildcards (`List<? extends Shape>`) with a generic parameter bound by a trait, or with `&[Box<dyn Shape>]`.

## Common mistakes
- Looking for a common base class `Object`. Rust has no universal base type; use `dyn Any` only for the rare case of real run-time typing.
- Expecting variance rules like `List<? super T>`. Rust uses lifetimes and traits instead.
- Adding bounds to the struct definition that only some methods need. Put bounds on the `impl` blocks or methods that use them.

## Related questions
### Is there anything like reflection to inspect `T`?
Not in the Java or C# sense. `type_name` and `size_of` exist, as above, and `Any` allows a checked downcast. Behaviour that depends on the type belongs in a trait.

### Do Rust generics make the executable larger?
Each used type gets its own copy of the code. This thread did not measure the effect on any program.

## Sources
- The Rust Book, "Generic Data Types": https://doc.rust-lang.org/book/ch10-01-syntax.html
- Java Tutorials, "Type Erasure": https://docs.oracle.com/javase/tutorial/java/generics/erasure.html
