Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between delegate in c# and function pointer in c++? [duplicate]

Tags:

Possible Duplicate:
are there function pointers in c#?

I'm interested in finding the difference between delegate in C# and function pointer in C++.

like image 244
Riporter Avatar asked Nov 11 '11 16:11

Riporter


People also ask

What is the difference between delegate and interface?

Delegates and Interfaces are two distinct concepts in C#. Interfaces allow to extend some object's functionality, it's a contract between the interface and the object that implements it, while delegates are just safe callbacks, they are a sort of function pointers.

What are delegates C?

A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate.

What are types of delegates?

There are two types of delegates, singlecast delegates, and multiplecast delegates.


2 Answers

A delegate in C# is a type-safe function pointer with a built in iterator.

It's guaranteed to point to a valid function with the specified signature (unlike C where pointers can be cast to point to who knows what). It also supports the concept of iterating through multiple bound functions.

In C#, delegates are multi-cast meaning they can iterate through multiple functions. For example:

class Program {    delegate void Foo();     static void Main(string[] args)    {       Foo myDelegate = One;       myDelegate += Two;        myDelegate(); // Will call One then Two    }     static void One()    {       Console.WriteLine("In one..");    }     static void Two()    {       Console.WriteLine("In two..");    } } 
like image 127
Mike Christensen Avatar answered Oct 05 '22 02:10

Mike Christensen


Delegates in C# can be either synchronous or asynchronous; C++ function pointers are synchronous unless you write your own multi-threading capability.

A pointer in C/C++ needn't refer to a full-blown object. C had function pointers and no object-oriented language support. Delegates are true function objects.

like image 23
duffymo Avatar answered Oct 05 '22 03:10

duffymo