5,696,038 members and growing! (13,141 online)
Email Password   helpLost your password?
Languages » C++ / CLI » General     Beginner License: The Code Project Open License (CPOL)

Delegates in managed C++

By Chris Maunder

This sample demonstrates single- and multi-cast delegates using C++, including declaration, creation and usage, and a discussion on type safety.
C++/CLI, VC7, C++, Windows, .NET, .NET 1.0VS.NET2002, Visual Studio, Dev

Posted: 25 Apr 2001
Updated: 15 Oct 2001
Views: 98,461
Bookmarked: 19 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
24 votes for this Article.
Popularity: 5.69 Rating: 4.13 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
1 vote, 20.0%
3
2 votes, 40.0%
4
2 votes, 40.0%
5

Introduction

Delegates are .NET's type safe equivalent to function pointers. Delegates go further than this though. Instead of a single delegate having the ability to point to, and invoke, a single function, delegates in .NET give you the ability to have a single delegate point to a list of methods, each which will be called in turn.

Creating a single cast delegate

A single cast delegate is one which points to a single method. To create a delegate you must first declare a delegate type that has the same signature as the methods you wish it to invoke. For instance, if we wished to have a delegate call a function that took a String* as a parameter and returned an int, we might declare it as

__delegate int MyDelegate(String *str);

Single cast delegates are implicitely derived from Delegate. To use a delegate to invoke your methods you must create an instance of the delegate and pass in an object and the method of that object you wish to call.

For instance, suppose we had a managed class

__gc class MyClass 
{
public:
	int MethodA(String *str) 
	{
		Console::WriteLine(S"MyClass::MethodA - The value of str is: {0}", str);
		return str->Length;
	}
}

we could declare an object of type MyClass and a delegate to call the objects methods like

MyClass *pMC = new MyClass();
MyDelegate *pDelegate = new MyDelegate(pMC, &MyClass::MethodA);

To invoke the object's method using the delegate is as simple as calling

pDelegate->Invoke("Invoking MethodA");

This would output:

MyClass::MethodA - The value of str is: Invoking MethodA

Creating a multi cast delegate

Multi cast delegates allow you to chain together methods so that each one will be called in turn when the delegate is invoked. To create a multicast method use the static Delegate::Combine method to combine delegates into a multicast delegate.

When creating multicast delegates in beta 1, you had to declare your delegates you wished to combine as multicast delegates using the __delegate(multicast) directive. This creates a delegate derived from MulticastDelegate. In beta 2 you do not use the (multicast) specifier, and you can use Delegate::Combine your single cast delegates into a multicast delegate.

Below is some sample code showing 2 multicast delegates being combined (beta 2)

// Declare a delegate

__delegate int MyDelegate(String *str);

// Create a simple managed reference class

__gc class MyClass 
{
public:
    int MethodA(String *str) 
    {
        Console::WriteLine(S"MyClass::MethodA - The value of str is: {0}", str);
        return str->Length;
    }

    int MethodB(String* str) 
    {
        Console::WriteLine(S"MyClass::MethodB - The value of str is: {0}", str);
        return str->Length * 2;
    }
};

...

MyClass *pMC = new MyClass();
MyDelegate *pDelegate1 = new MyDelegate(pMC, &MyClass::MethodA);
MyDelegate *pDelegate2 = new MyDelegate(pMC, &MyClass::MethodB);

MyDelegate *pMultiDelegate = 
	static_cast<MyDelegate *>(Delegate::Combine(pDelegate, pDelegate2));

When you invoke the multicast delegate pMultiDelegate it will first call MyClass::MethodA, then MyClass::MethodB. For instance, calling

pMultiDelegate->Invoke("Invoking Multicast delegate");

would result in

MyClass::MethodA - The value of str is: Invoking multicast delegate
MyClass::MethodB - The value of str is: Invoking multicast delegate

Type Safety

Delegates are inherently type safe. You cannot compile calls to a delegate using the wrong parameters, or assign the return value of a delegate to a type that cannot be implicitly cast from the return type of the method the delegate is calling. Because an object and method are passed to the delegates constructor, the compiler has all the information it needs to ensure that errors caused by mismatched parameters and return types do not occur.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Chris Maunder


Sitebuilder, Financialadmin, Editor, Staff, Admin
Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.

His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.

He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.

Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.
Occupation: Founder
Company: The Code Project
Location: Canada Canada

Other popular C++ / CLI articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
Generalplease show C++ equivelentmemberTomM4:57 8 Apr '02  
GeneralManaged C++ / C#memberAnonymous2:27 19 Oct '01  
GeneralC++ dos not need thismemberJoaquín M López Muñoz11:15 18 Oct '01  
GeneralAnd funtion objects?memberNemanja Trifunovic6:56 17 Oct '01  
GeneralWhy C++ managed extensions?memberGerald Schwab19:40 30 Apr '01  
GeneralRe: Why C++ managed extensions?memberChris Maunder19:55 30 Apr '01  
GeneralRe: Why C++ managed extensions?memberGerald Schwab20:12 30 Apr '01  
GeneralRe: Why C++ managed extensions?memberSoliant12:09 19 Jun '02  
GeneralRe: Why C++ managed extensions?memberChristopher Lord12:57 17 Aug '03  
GeneralScootermemberCodeGuy6:41 26 Apr '01  
GeneralRe: ScootermemberChris Maunder17:41 26 Apr '01  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Oct 2001
Editor: Chris Maunder
Copyright 2001 by Chris Maunder
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project