Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C++/CLI
Article

Delegates in managed C++

Rate me:
Please Sign up or sign in to vote.
3.80/5 (4 votes)
15 Oct 2001CPOL2 min read 156.7K   977   27   11
This sample demonstrates single- and multi-cast delegates using C++, including declaration, creation and usage, and a discussion on type safety.

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)


Written By
Founder CodeProject
Canada Canada
Chris Maunder is the co-founder of CodeProject and ContentLab.com, and has been a prominent figure in the software development community for nearly 30 years. Hailing from Australia, Chris has a background in Mathematics, Astrophysics, Environmental Engineering and Defence Research. His programming endeavours span everything from FORTRAN on Super Computers, C++/MFC on Windows, through to to high-load .NET web applications and Python AI applications on everything from macOS to a Raspberry Pi. Chris is a full-stack developer who is as comfortable with SQL as he is with CSS.

In the late 1990s, he and his business partner David Cunningham recognized the need for a platform that would facilitate knowledge-sharing among developers, leading to the establishment of CodeProject.com in 1999. Chris's expertise in programming and his passion for fostering a collaborative environment have played a pivotal role in the success of CodeProject.com. Over the years, the website has grown into a vibrant community where programmers worldwide can connect, exchange ideas, and find solutions to coding challenges. Chris is a prolific contributor to the developer community through his articles and tutorials, and his latest passion project, CodeProject.AI.

In addition to his work with CodeProject.com, Chris co-founded ContentLab and DeveloperMedia, two projects focussed on helping companies make their Software Projects a success. Chris's roles included Product Development, Content Creation, Client Satisfaction and Systems Automation.

Comments and Discussions

 
Generalplease show C++ equivelent Pin
TomM8-Apr-02 3:57
TomM8-Apr-02 3:57 
It would be useful & interesting if you would compare this to the standard C++ equivelent.

Tom
GeneralManaged C++ / C# Pin
19-Oct-01 1:27
suss19-Oct-01 1:27 
GeneralC++ dos not need this Pin
Joaquín M López Muñoz18-Oct-01 10:15
Joaquín M López Muñoz18-Oct-01 10:15 
QuestionAnd funtion objects? Pin
Nemanja Trifunovic17-Oct-01 5:56
Nemanja Trifunovic17-Oct-01 5:56 
QuestionWhy C++ managed extensions? Pin
Gerald Schwab30-Apr-01 18:40
Gerald Schwab30-Apr-01 18:40 
AnswerRe: Why C++ managed extensions? Pin
Chris Maunder30-Apr-01 18:55
cofounderChris Maunder30-Apr-01 18:55 
GeneralRe: Why C++ managed extensions? Pin
Gerald Schwab30-Apr-01 19:12
Gerald Schwab30-Apr-01 19:12 
GeneralRe: Why C++ managed extensions? Pin
TigerNinja_19-Jun-02 11:09
TigerNinja_19-Jun-02 11:09 
GeneralRe: Why C++ managed extensions? Pin
Christopher Lord17-Aug-03 11:57
Christopher Lord17-Aug-03 11:57 
GeneralScooter Pin
CodeGuy26-Apr-01 5:41
CodeGuy26-Apr-01 5:41 
GeneralRe: Scooter Pin
Chris Maunder26-Apr-01 16:41
cofounderChris Maunder26-Apr-01 16:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.