tags:

views:

352

answers:

5

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

for example:

        iCalendar iCal = new iCalendar();
        Event evt = iCal.Create<Event>();

Google can't help, but I know SO can!

+7  A: 

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
I wish I could pick two correct answers. Thanks a million :D
DrG
+14  A: 

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

CMS
Thanks, exactly what I was looking for. Thx buddy
DrG
A: 

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
A: 

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
+1  A: 

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