0

I studied Java for a long time and am well acquainted with the operation of generic types in the language : I know there are only at compile time , suffering type erasure at the end of it ( so that at runtime this information is not available ) and have some notion of the difficulties when applying polymorphism on generic types .

Now I am learning C # , and I noticed that although this language use similar notation ( Type ) semantics does not seem the same . For example , to see that question did the C # runtime stores the information of the generic types instead of discarding it , unlike Java, is that correct? Also, I have never seen an example in C # that utilizes " jokers " ( wildcards ) and type < ? extends TipoGenerico > . This is possible ( or even necessary ) in that language ?

Finally , C # supports individual methods ( not just classes ) generics ? If yes , what is the equivalent syntax of this construction in Java :

public <T> void method (T parameter1 , parameter2 <T> List ) {

If there are any additional details that deserves emphasis , or maybe some reference material to learn more , will also be welcome.

fge
  • 119,121
  • 33
  • 254
  • 329
denes bastos
  • 29
  • 2
  • 5
  • While that question is similar, it doesn't address some of the specific issues here. I don't know that it's an exact duplicate... – Reed Copsey Mar 21 '14 at 19:54

2 Answers2

4

For example , to see that question did the C # runtime stores the information of the generic types instead of discarding it , unlike Java, is that correct?

Yes, this is correct. C# doesn't suffer from the limitations of type erasure in this way.

Also, I have never seen an example in C # that utilizes " jokers " ( wildcards ) and type < ? extends TipoGenerico > . This is possible ( or even necessary ) in that language ?

Yes, this is done via generic constraints, for example:

public class SomeType<T> where T : IEquatable<T> 
{

This will create a class where the type T must implement IEquatable<T>.

Finally , C # supports individual methods ( not just classes ) generics ? If yes , what is the equivalent syntax of this construction in Java :

public void Method<T>(T parameter1, List<T> parameter2)
{
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

Yes, C# does not do type erasure, it does generics the right way. Wildcards are achieved by the where clause where you specify contraints in a similar way to your generic type.

http://msdn.microsoft.com/en-us/library/bb384067.aspx

Yes, C# includes method generics:

public void method<T>(T p1, T p2) 

is the syntax

David Conrad
  • 15,432
  • 2
  • 42
  • 54
Simon
  • 2,840
  • 2
  • 18
  • 26