❔ What is the use of datatype after function name?
I have a function signature that looks like this:
What is the use of <T> after the function name?
10 Replies
That's a type parameter
It essentially lets you pass a type as a parameter to a function
Generic Methods - C# Programming Guide
Learn about methods declared with type parameters, known as generic methods. See code examples and view additional available resources.
T
in this case is constrained to implementing the IEntity
interface.
I.e. when you call AddMongoRespository
, the type you specify in the <>
has to implement IEntity
.This function is actually a part of generic service, one of the lines inside the function is :
So if I need to use
<T>
anywhere inside the function its important to pass a type parameter while function call?
so both of these functions are right. Is this correct understanding?The second one adds an
IRepository
of specifically IEntity
.
The first adds an IRepository
of a specific type (which still implements IEntity
).so both are correct syntax right?
so in the second case I could simply call the function without specifuying the type in
<>
In the second one, if you call
services.GetService<IRepository<SomeEntity>>()
then it'll throw an exception.
It'll only work if you do services.GetService<IRepository<IEntity>>()
yes, that makes sense.
Since I assume the point of
IRepository
is to contain entities of a specific type, the first one is correct.Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.