Content deleted Content added
MichaelMaggs (talk | contribs) Adding local short description: "Programming language concept", overriding Wikidata description "subtyping property of a generic type in a programming language" |
m Add reference for for C#. |
||
Line 32:
* {{C sharp|Action<Animal>}} is a subtype of {{C sharp|Action<Cat>}}. The subtyping is reversed because {{C sharp|Action<T>}} is '''contravariant''' on {{C sharp|T}}.
* Neither {{C sharp|IList<Cat>}} nor {{C sharp|IList<Animal>}} is a subtype of the other, because {{C sharp|IList<T>}} is '''invariant''' on {{C sharp|T}}.
The variance of a C# generic interface is declared by placing the {{C sharp|out}} (covariant) or {{C sharp|in}} (contravariant) attribute on (zero or more of) its type parameters.<ref>{{cite book |last=Skeet|first=Jon|title= C# in Depth |publisher= Manning |page= 144 |isbn= 978-1617294532}}</ref> For each so-marked type parameter, the compiler conclusively verifies, with any violation being fatal, that such use is globally consistent. The above interfaces are declared as {{C sharp|IEnumerable<out T>}}, {{C sharp|Action<in T>}}, and {{C sharp|IList<T>}}. Types with more than one type parameter may specify different variances on each type parameter. For example, the delegate type {{C sharp|Func<in T, out TResult>}} represents a function with a '''contravariant''' input parameter of type {{C sharp|T}} and a '''covariant''' return value of type {{C sharp|TResult}}.<ref>[http://msdn.microsoft.com/en-us/library/bb549151.aspx Func<T, TResult> Delegate] - MSDN Documentation</ref><ref>{{cite book |last=Skeet|first=Jon|title= C# in Depth |publisher= Manning |page= 145 |isbn= 978-1617294532}}</ref>
The [[#Interfaces|typing rules for interface variance]] ensure type safety. For example, an {{C sharp|Action<T>}} represents a first-class function expecting an argument of type {{C sharp|T}},<ref>{{cite book |last=Skeet|first=Jon|title= C# in Depth |publisher= Manning |page= 144 |isbn= 978-1617294532}}</ref> and a function that can handle any type of animal can always be used instead of one that can only handle cats.
== Arrays ==
|