C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# Delegates CovarianceC# Delegate Covariance allows us to call a method that has derived return type of the delegate signature return type. It means we can call a method that returns parent or child class object. Here, we are creating two examples. First example calls a method that returns a parent or derived class object. C# Delegate Covariance Example 1
using System;
namespace CSharpFeatures
{
class A { }
class B : A { }
class DelegateCoveriance
{
delegate A Mydelegate();
static void Main(string[] args)
{
// Calling MethodA
Mydelegate del = MethodA;
del();
// Calling MethodB
Mydelegate del2 = MethodB;
del2();
}
static A MethodA()
{
Console.WriteLine("This is MethodA");
return new A();
}
static B MethodB()
{
Console.WriteLine("This is MethodB");
return new B();
}
}
}
Output: This is MethodA This is MethodB C# Delegate Covariance Example 2
In this example, we are calling a method that does not return derived object as specified in delegate signature. Let's see what happen, if we do this.
using System;
namespace CSharpFeatures
{
class A { }
class B : A { }
class C { }
class DelegateCoveriance
{
delegate A Mydelegate();
static void Main(string[] args)
{
// Delegating MethodA
Mydelegate del = MethodA;
del();
// Delegating MethodB
Mydelegate del2 = MethodB;
del2();
Mydelegate del3 = MethodC;
del3();
}
static A MethodA()
{
Console.WriteLine("This is MethodA");
return new A();
}
static B MethodB()
{
Console.WriteLine("This is MethodB");
return new B();
}
static C MethodC()
{
Console.WriteLine("This is MethodC");
}
}
}
Output: DelegateCoveriance.cs(25,31): error CS0407: 'CSharpFeatures.C CSharpFeatures.DelegateCoveriance.MethodC()' has the wrong return type
Next TopicC# Delegate Inference
|