Reader Level:
ARTICLE

Implementing Delegates in C#

On February 04, 2001 Articles | C# Programming
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.
  • 0
  • 0
  • 26180
Download Files:
 

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 TVanover@Quilogy.Com
///
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));
}
}
}

TimothyA Vanover

I have been coding since 1996, and have experience in C, most flavors of Basic, HTML, T-SQL, and since the PDC release have managed to pick up some VB.Net and C Sharp. I have been employed for the las...

  • 398rank
  • 192K readers
COMMENT USING

Trending up