User Tools

Site Tools


notes:csharp:delegates

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
notes:csharp:delegates [2020/01/17]
leszek [Delegate Type Variance]
notes:csharp:delegates [2020/01/17] (current)
leszek [Generic Delegate Type Parameter Variance]
Line 243: Line 243:
  
  
-====Generic Delegate Type Parameter Variance==== 
  
-  * Mark a type parameter used only on the return value as covariant (out). 
-  * Mark any type parameters used only on parameters as contravariant (in). 
- 
-<code csharp> 
-namespace ConsoleTest 
-{ 
-    // A delegate that supports covariance. 
-    public delegate T Delegate1<​out T>(); 
- 
-    // A delegate that supports contravariance. 
-    public delegate void Delegate2<​in T>(T arg); 
- 
-    class Program 
-    { 
-        // handlers 
-        public static T Method1<​T>​() { T n = default(T); return n; } 
-        public static void Method2<​T>​(T arg) { } 
- 
-        static void Main() 
-        { 
-            // A delegate that supports covariance. 
-            Delegate1<​string>​ d1 = Method1<​string>;​ 
- 
-            // Covariance enables this assignment. 
-            Delegate1<​object>​ o1 = d1; 
- 
-            // ... 
- 
-            // A delegate that supports contravariance. 
-            Delegate2<​object>​ d2 = Method2<​object>;​ 
- 
-            // Contravariance enables this assignment. 
-            Delegate2<​string>​ o2 = d2; 
-        } 
-    } 
-} 
-</​code>​ 
  
  
notes/csharp/delegates.txt ยท Last modified: 2020/01/17 by leszek