Reputation: 2746
What does the following syntax mean? Specifically the <> braces? (Can't seem to google it)
public T Execute<T>(RestRequest request) where T : new()
{ .... }
Here's what I understand;
public
= the visibility of the function.
T
= the return type (probably defined somewhere else in code)
(RestRequest request)
= the function parameter list. request
is the lone parameter
The remaining bits - Execute<T> ... where T : new()
is strange and new to me.
Possibly related, but what does the following actually return? (as in; does it return a function or an object or a reference to something?)
return Execute<Call>(request);
Both the code snippets were taken from the RestSharp documentation wiki example code - https://github.com/restsharp/RestSharp/wiki/Recommended-Usage
Upvotes: 1
Views: 5109
Reputation: 677
Here it is a constraint on the generic parameter. Generic classes and methods combine reusability, type safety and efficiency. The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.
http://msdn.microsoft.com/en-us/library/0x6a29h6.aspx
http://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx
Upvotes: 0
Reputation: 1478
Here represents type of your collection it could be predefined datatype or user defined datatype like any class
Upvotes: 0
Reputation: 125620
The remaining bits -
Execute<T> ... where T : new()
is strange and new to me.
So, Execute
is method name. <T>
is generic parameter T
(See Generics (C# Programming Guide)) and where T : new()
is generic constraint, which requires T
to have parameterless constructor.
Possibly related, but what does the following actually return? (as in; does it return a function or an object or a reference to something?)
return Execute<Call>(request);
Because Execute<T>
returns T
and you call is with T = Call
this one will return Call
class instance (or possible null
if only Call
is class
, not struct
).
Upvotes: 2
Reputation: 127543
T
= the return type (probably defined somewhere else in code)
Actually it is defined between the <>
. When you go to call this function you put your own type in the brackets, so in your return Execute<Call>(request);
turns in to the function signature public Call Execute(RestRequest request);
The where T : new()
is a limitation on what you can put inside the brackets, what you are declaring is whatever is going to be passed in as T
must implment a default constructor that is public (that is what new()
means.
Upvotes: 2