7 ms·
Does C# handle generics better than Java?
by mrkeen 6y ago
Does C# handle generics better than Java?
- LandR 6y agoC# generics are reified.
- accountLost 6y agoYou can't easily create a instance of the generic type in java. for example : return new T(); is possible in C#, not in java.
- ohgodplsno 6y agoThere is a way-ish, which is passing a Class<T> as an additional parameter and doing clazz.newInstance(). Definitely not pleasant though.
- Felk 6y agoFor that particular use case it may be better to pass a constructor reference / new instance supplier to not rely on reflection.
- Felk 6y agoAs "better" isn't clearly defined, here are some things that some people might consider superior: - primitives or any custom value types/structs can be used. No need for boxing or method duplication for primitives. - type information available at runtime, no need to pass 'Class<T>' parameters. - type constraint 'new' available, which means it must have a default constructor so you can do 'new T()'. No need to use reflection or pass a constructor parameter. - type constraint 'notnull' available - class-scoped compiler enforced covariance and contravariance, though I think you can get similar results with java's "? extends T" and "? super T" constraints
- paavohtl 6y agoC# implements proper reified generics. Generic types parameterised with different types are actual types in C#, while in Java generics is basically just syntax sugar for avoiding type casts. Each element in a List<byte> in C# takes 8 bits, while in Java each element in a ArrayList<Byte> is actually just an Object and therefore is a pointer (64 bits) to a separate allocation.
- kaba0 6y agoBut at the same time, reified types will create a separate object for each template type, making some optimizations happen only for a type that was used often. While in Java, ArrayList for example will benefit regardless of the concrete type.