C
C#3y ago
Keeda

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
Thinker
Thinker3y ago
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.
Thinker
Thinker3y ago
wait no other way around
Keeda
KeedaOP3y ago
But isn't all of that gonna work the same with same normal declaration like "public delegate int Comparison<T>(T left, T right);"?
Thinker
Thinker3y ago
Comparison<object> objectComparison = (left, right) => /* compare left and right somehow */;
Comparison<string> stringComparison = objectComparison;
Comparison<object> objectComparison = (left, right) => /* compare left and right somehow */;
Comparison<string> stringComparison = objectComparison;
Keeda
KeedaOP3y ago
oh sorry nvm
Thinker
Thinker3y ago
in just allows this to work
Keeda
KeedaOP3y ago
oh okay thankss!
Thinker
Thinker3y ago
Because string inherits from object then you can use a Comparison<object> as a Comparison<string> There also exists out which does the exact opposite
Keeda
KeedaOP3y ago
opposite in sense
Thinker
Thinker3y ago
yeah
Keeda
KeedaOP3y ago
like we could convert trom string to object?
Thinker
Thinker3y ago
yes
Keeda
KeedaOP3y ago
Alright thank you!
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server