48

I've seen this syntax a couple times now, and it's beginning to worry me,

For example:

iCalendar iCal = new iCalendar();
Event evt = iCal.Create<Event>();
Ian G
  • 29,468
  • 21
  • 78
  • 92

5 Answers5

40

It's a Generic Method, Create is declared with type parameters, and check this links for more information:

R.D. Alkire
  • 502
  • 1
  • 5
  • 14
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 8
    -1 for what essentially amounts to a link only answer. While those links are great for further reference, It would be great if their contents were summarized by your post in greater detail than one sentence. – GiantCowFilms Aug 20 '18 at 18:31
28

It's calling a generic method - so in your case, the method may be declared like this:

public T Create<T>()

You can specify the type argument in the angle brackets, just as you would for creating an instance of a generic type:

List<Event> list = new List<Event>();

Does that help?

One difference between generic methods and generic types is that the compiler can try to infer the type argument. For instance, if your Create method were instead:

public T Copy<T>(T original)

you could just call

Copy(someEvent);

and the compiler would infer that you meant:

Copy<Event>(someEvent);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

It's the way you mention a generic method in C#.

When you define a generic method you code like this:

return-type MethodName<type-parameter-list>(parameter-list)

When you call a generic method, the compiler usually infers the type parameter from the arguments specified, like this example:

Array.ForEach(myArray, Console.WriteLine);

In this example, if "myArray" is a string array, it'll call Array.ForEach<string> and if it's an int array, it'll call Array.ForEach<int>.

Sometimes, it's impossible for the compiler to infer the type from the parameters (just like your example, where there are no parameters at all). In these cases, you have to specify them manually like that.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
1

It is a generic method that implements the Factory Method pattern.

user33675
  • 1,473
  • 11
  • 11
0

This syntax is just applying generics to a method. It's typically used for scenarios where you want to control the return type of the method. You will find this kind of syntax a lot in code that uses a IoC framework.

lvaneenoo
  • 219
  • 1
  • 5