Variance in C# 4.0

Your Ad Here

Variance is of two types
1: Covariance
2: ContraVariance

It used to be that an IEnumerable/ wasn’t an IEnumerable/. Now C# allows “co-and contravariance” and common BCL types are updated to take advantage of that.
The C# compiler allows you to call a method with any name and any arguments on d because it is of type dynamic. At runtime the actual object that d refers to will be examined to determine what it means to “call M with an int” on it.
The type dynamic can be thought of as a special version of the type object, which signals that the object can be used dynamically. It is easy to opt in or out of dynamic behavior: any object can be implicitly converted to dynamic, “suspending belief” until runtime. Conversely, there is an “assignment conversion” from dynamic to any other type, which allows implicit conversion in assignment-like constructs:

dynamic d = 7; // implicit conversion
int i = d; // assignment conversion

Complete Example for variance

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearnVarianceUse
class Shape { }
class Square: Shape { }

class Program
// Declaring delegates
delegate T Func1();
delegate void Action1(T a);

static void Main(string[] args)
// Creating the funcSquare function which takes no parameters , see empty ()
Func1 funcSquare = () => new Square();

// Assigning the funcSquare to funcShape type Func and it is variance which is possible only in c#4.0
// it gives compile time error in c#3.0
Func1 funcShape = funcSquare;

* In the next line, we are creating a function which is called by delegate and , we
* are passing someobject which is simply printed on the console.
* */
Action1 actionShape = (objParameter) => { Console.WriteLine(objParameter); };

/* In Next line, We are assigning the actionShape Type delegate to the
* actionSquare type which was not allowed in c#3.0 but now it is possible to
* use this variance , you can use base type of delegate to inherited
* type
* */

Action1 actionSquare = actionShape;

actionShape(new Shape()); // same type of object is used
actionShape(new Square()); // inherited type of object is used

if you have any queries , please email me.
Happy Coding.

Posted in Labels: kick it on |


  1. Anonymous Says: