27

I'm a VB.Net guy. (because I have to be, because the person who signs my check says so. :P) I grew up in Java and I don't generally struggle to read or write in C# when I get the chance. I came across some syntax today that I have never seen, and that I can't seem to figure out.

In the following method declaration, what does < T > represent?

static void Foo < T >(params T[] x)

I have seen used in conjunction with declaring generic collections and things, but I can't for the life of me figure out what it does for this method.

In case it matters, I came across it when thinking about some C# brain teasers. The sixth teaser contains the entire code snippet.

Drew
  • 817
  • 1
  • 11
  • 17

4 Answers4

34

what you are asking is the concept of the generics in c#. By using generics you can use this method for the types you want

suppose you have to create a function to add two numbers. In that case, your function is

//For integer :
public int sum(int a, int b)
{ 
  return a + b;
}



//For floating point numbers :
public float sum( float a, float b)
{
  return a + b;
}

Following this logic, if you want a function that will sum two double type numbers you would create one more function, and so on.

Note: code above will not work with C#, but it for explaining concept easily, it just sudo code it will work with C# if you have nullable type or reference type easily or one need to write logic to convert value to primary type.

Bu with the help of generics you can replace all of these functions and write the following,

public T sum<T>(T a, T b)
{
  return a + b;
}

This will work for all numeric types, as well as for strings.

check this out for more detail : http://www.codeproject.com/kb/books/EssentialCS20.aspx

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 5
    +1 for code Sample and easy to follow example! Shows a clear understanding of the Question asked and the OP's level of understanding. – Armstrongest Apr 30 '10 at 16:03
  • 2
    The example is easy to understand, however it doesnt work. You cant add two variables of generic type T. See: http://stackoverflow.com/questions/32664/c-generic-constraint-for-only-integers The workaround is to use generic operators from an external library: http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html – Philip Daubmeier Apr 30 '10 at 16:23
  • Thanks for the information i got to know it more towards c++ templates – Pranay Rana Apr 30 '10 at 16:45
24

This defines a generic method, which is one form of generics, which were added to C# in C# 2.0.

The method sig should be:

static void Foo<T>(params T[] x)
{ // ...

This lets you pass any number of arguments of any (specific) type into the method Foo, and it acts on that array of arguments. It's similar to how generic types work, except scoped just to the method. The <T> specifies the type of the argument being passed into the method, so you can call this like:

Foo<MyClass>(myClassInstance, myClassInstance2, mySubclassInstance);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Specifically, it defines the name (or names) use for the generic type(s) in the method. – Adam Robinson Apr 30 '10 at 15:53
  • 2
    My understanding is that in this code, (params T[] x) is responsible for declaring that the method takes any number of arguments of type T and stores them in an array referenced by x. If that is correct, what does the < T > after the method name add to the declaration? – Drew Apr 30 '10 at 16:02
  • Perhaps it allows the caller to be more verbose in describing the type of the variables passed as parameters. Would I be able to call Foo with a line that read Foo(myClassInstance, myClassInstance2) as long as myClassInstance and myClassInstance2 are of the same type? – Drew Apr 30 '10 at 16:04
  • 3
    @Drew: you declare a type you want to use in the function. The compiler wouldnt know what you mean with `T[]`, because there is no type `T`, it is declared with the ``. As a caller of the function you can then set the type. e.g. `Foo(1, 2, 3);` or `Foo(1.0, 2.0, 3.0);` – Philip Daubmeier Apr 30 '10 at 16:07
  • 1
    @Drew: its like with variable declarations, you can use any name you wish. you could also write: `static void Foo(params Bar[] x) { }`. It is just a convention to use `T`, or `TKey` and `TValue` for a dictionary for example. – Philip Daubmeier Apr 30 '10 at 16:08
  • 5
    @Drew: Also note that you can omit the `` when calling the function as long as it can be inferred by the compiler. For example, `Foo(new Bar(), new Bar())` is equivalent to `Foo(new Bar(), new Bar())`. An example of when the compiler can't work out what type it should use might be when passing in several objects of different types witha a common base type, or an anonymous method. – Will Vousden Apr 30 '10 at 16:19
2

The T is a type parameter and in this case can be anything (a constraint may be specified, but here there is no constraint). Without this feature you would have to declare the method for every type you plan to use:

static void Foo(params int[] x)    
static void Foo(params string[] x)    
static void Foo(params Customer[] x)    
etc...

More information on generics can be found on MSDN: Introduction to Generics (C#).

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

That is the Generic Type parameter of a Generic Method.

Once you specify a type for T when calling the method, .NET can ensure type safety based on that type parameter.

static void Foo<T>(params T[] x) { }

would be called like:

string[] names = new string[] {"Foo", "Bar", "Baz"};

Foo<string>(names);

but this would cause a compiler error:

int[] nums = new int[] {1, 2, 3};

Foo<string>(nums); // nums is not string[]
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536