Implementing Delegates in C#


The Zip file contains two projects. One is VB.Net and the other is C#. Each project is an example of the same use of a delegate. A base class is derived and the delegate calls a method on several classes derived from the base class. Several things are shown from this example. Using inherited base types to strinct type checking of a base type and calling class level methods from a single delegate.

Here is sample code from Delegates.cs file:

namespace DelegatesCS
{
using
System;
/// <summary>

///
Author [email protected]
///
Date 02/02/2001
///
Purpose Example of Delegate usage
/// </summary>

public class Wisdom
//class containing the Delegate
{
public delegate string
GiveAdvice();
public string
OfferAdvice(GiveAdvice Words)
{
return
Words();
}
}
public class Parent
//base class
{
public virtual string
Advice()
{
return
("Listen to reason");
}
~Parent() {}
}
public class Dad: Parent
//derive from the parent
{
public
Dad() {}
public override string
Advice()
{
return
("Listen to your Mom");
}
~Dad() {}
}
public class Mom: Parent
//derive from the parent
{
public
Mom() {}
public override string
Advice()
{
return
("Listen to your Dad");
}
~Mom() {}
}
public class Daughter
//don't derive from the parent
{
public
Daughter() {}
public string
Advice()
{
return
("I know all there is to life");
}
~Daughter() {}
}
public class
Test
{
public static string CallAdvice(Parent p)
//use the base type of derived class
{
Wisdom parents =
new
Wisdom();
Wisdom.GiveAdvice TeenageGirls =
new
Wisdom.GiveAdvice(p.Advice);
return
(parents.OfferAdvice(TeenageGirls));
}
public static void
Main()
{
Dad d =
new
Dad();
Mom m =
new
Mom();
Daughter g =
new
Daughter();
//these both derived from the base class
Console.WriteLine(CallAdvice(d));
Console.WriteLine(CallAdvice(m));
//cannot do this as it did not derive from the base
//Console.WriteLine(CallAdvice(g));
}
}
}

Up Next
    Ebook Download
    View all
    Learn
    View all