C
C#2y 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
Thinker2y 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
Thinker2y ago
wait no other way around
Keeda
Keeda2y 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
Thinker2y 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
Keeda2y ago
oh sorry nvm
Thinker
Thinker2y ago
in just allows this to work
Keeda
Keeda2y ago
oh okay thankss!
Thinker
Thinker2y 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
Keeda2y ago
opposite in sense
Thinker
Thinker2y ago
yeah
Keeda
Keeda2y ago
like we could convert trom string to object?
Thinker
Thinker2y ago
yes
Keeda
Keeda2y ago
Alright thank you!
Accord
Accord2y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server
More Posts