2

Can anyone tell me the difference between

public T Get<T>(int id)

and

public T Get(int id)
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • indicates a generic type parameter which is defined at runtime. This type is either specified during class instantiation (your second line would need to have had T defined during object creation) or when the method is called (your first line of code). – Dave New Jun 25 '12 at 11:39
  • @davenewza: Your comment is correct both cases and actually is generic for ant generics. Something like "What does T mean here?" or "What is generics?" ;) – abatishchev Jun 25 '12 at 11:45

3 Answers3

7

Compare:

class First
{
    public T Get<T>(int id) // T is declared in the method scope
    {
    }
}

and

class Second<T>
{
    public T Get(int id) // T is declared in the class scope
    {
    }
}

Also there is a 3rd scenario:

class Third<U>
{
    public T Get<T>(int id) // T is declared in the method scope when class scope has another generic argument declared
    {
    }
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • 1
    +1, and let me add that the confusion between these two cases is what leads to questions like this: http://stackoverflow.com/questions/6740978/type-parameter-t-has-the-same-name-as-the-type-parameter-from-outer-type – s.m. Jun 25 '12 at 11:36
  • 1
    Don't forget the case where there is a type called `T` (don't do that!) – George Duckett Jun 25 '12 at 11:52
4

The difference is that you use the first type of declaration if this is when T hasn't been defined before. ie.

public class MyClass
{
    public T Get<T>(int id);
}

And the second when T has already been defined at the class level. ie.

public class MyClass<T>
{
    public T Get(int id);
}

In this case you can also use the first type of declaration - this is effectively shorthand. There is no difference in the effect.

Edit In fact, the second declaration only requires that T be in scope, another example would be a nested class as in...

public class MyClass<T>
{
  public class NestedClass
  {
    public T Get(int i);
  }
}
Michael
  • 8,891
  • 3
  • 29
  • 42
0

Read about Generics before you can use them in code.

Ebad Masood
  • 2,389
  • 28
  • 46