Hi I want to know about this in keyword used in the attached image. [Answered]
I know "in" keyword when used with method parameters but I am unable to understand the same in this context. What is the use of 'in' before placeholder type 'T'?
15 Replies
in
is kind of weird
Firstly, it specifies that T
can only be used as a parameter
Secondly, it specifies that if you have a class B
that inherits from A
, then you can convert a Comparison<A>
to a Comparison<B>
.
In fancy terms this is called "contravariance", the idea that you can convert a generic type to the same type but with a more derived generic type.wait no other way around
But isn't all of that gonna work the same with same normal declaration like "public delegate int Comparison<T>(T left, T right);"?
oh sorry nvm
in
just allows this to workoh okay thankss!
Because
string
inherits from object
then you can use a Comparison<object>
as a Comparison<string>
There also exists out
which does the exact oppositeopposite in sense
yeah
like we could convert trom string to object?
yes
Alright thank you!
✅ This post has been marked as answered!