Click here to Skip to main content
15,879,326 members
Everything / Delegates

Delegates

delegates

Great Reads

by Sergey Alexandrovich Kryukov
Derived work based on the article by Sergey Ryazanov "The Impossibly Fast C++ Delegates": this good solution is fixed and further developed using C++11.
by David Lafreniere
A C++17 standards compliant delegate library capable of targeting any callable function synchronously or asynchronously
by Anton Chibisov
This tutorial showcases how to implement C++ delegates which are capable of being bound to methods and functions having arbitrary signature, i.e., any number and type of parameters and return value.
by Muraad Nofal
A haskell monad/(applicative)functor like interface in C# that extends IEnumerable.

Latest Articles

by David Lafreniere
A C++ standards compliant delegate library capable of targeting any callable function synchronously or asynchronously
by David Lafreniere
A C++17 standards compliant delegate library capable of targeting any callable function synchronously or asynchronously
by yutaraa
Get, move, copy and delete event handler delegates of Windows form controls.
by Jon McKee
How to do it and why it works

All Articles

Sort by Score

Delegates 

11 Mar 2017 by Sergey Alexandrovich Kryukov
Derived work based on the article by Sergey Ryazanov "The Impossibly Fast C++ Delegates": this good solution is fixed and further developed using C++11.
19 Dec 2022 by David Lafreniere
A C++17 standards compliant delegate library capable of targeting any callable function synchronously or asynchronously
13 Apr 2015 by Anton Chibisov
This tutorial showcases how to implement C++ delegates which are capable of being bound to methods and functions having arbitrary signature, i.e., any number and type of parameters and return value.
18 Sep 2013 by Muraad Nofal
A haskell monad/(applicative)functor like interface in C# that extends IEnumerable.
6 Jan 2017 by Akhil Mittal
This article of the series "Diving into OOP" will explain all about events in C#. The article focusses more on practical implementations and less on theory.
22 Aug 2013 by OriginalGriff
Neither the Expression or the params are datatypes: the former is similar to Func but returns a tree rather than a value (There is a good description here: http://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-rather-than-funct[^]).params is a C# keyword that lets you...
24 Nov 2011 by Scanix
SystemFramework defines interfaces, classes, and types to support a native runtime system with its own garbage collector, delegates, etc. The design of SystemFramework classes is similar to those of the .NET Framework.
28 May 2014 by OriginalGriff
Well no - they won't. You aren't calling them at all - you are just adding them to the list of methods to call when you do action the delegate. In fact, each time you press the button, you add four more methods to the list, so if you did call the delegate itself, after the first press it would...
30 May 2014 by Raul Iloc
1. ExampleDelgate e3 = e1 + e2; create an delegate object e3 as sum of e1 and e2 this is similar with the adding into an "event" two methods, in this case the list will have the next 2 methods: Add and mul.So if you will invoke e3(20, 10); ==> both methods Add(20, 10) and mul(20,10) will be...
26 Mar 2017 by Danilow
Simulating C# event handlers in Java
9 Dec 2011 by thatraja
Better check these threadswhen & why to use delegates?[^]Why do we need C# delegates[^]Advantages of using delegates?[^]Delegates, Why?[^]
9 Dec 2011 by Uday P.Singh
already answered:What is delegate..? What is the use of it..?[^]hope it helps :)
23 Dec 2012 by Mehdi Gholam
Posted from the comment:Check if the "optimize code" is set in your project.
30 May 2014 by Thomas Daniels
Change the return type of your delegate from void to int:public delegate int ExampleDelgate (int x, int y);Also, when you try to access the mul method with a delegate, you should pass 30 and 10 as parameters and not as a multiplication:ed = new ExampleDelgate(Democlass.mul);//ed(30...
30 May 2014 by Sergey Alexandrovich Kryukov
In addition to the correct Solution 1:You don't need a separate delegate type declaration for such a simple signature; it is already done for you and is System.Func. You don't need a separate type declaration at all:System.Func ed = new System.Func
6 Jan 2015 by Matt T Heffron
If I understand your question, you've almost got it correct in your code above: class Program { static void Main(string[] args) { somedelegate process = new somedelegate(someclass.somemethod); // NOTE: no parens () process(4); } ...
6 Jan 2015 by Sergey Alexandrovich Kryukov
Solution 1 is only good for static methods. Yes, you asked about static methods, but this is not the only possibility. But this is also possible with the class instance. Compare: delegate int SomeDelegate(int i); class Implementation { internal int SomeMethod(int i) { /*...
2 Apr 2016 by OriginalGriff
Delegates are used for more than just "call this or that" - they can provide a "chain of methods to be called" for example. You use delegates already, quite a bit - you just don't realize it because they are "hidden" at the core of Event handling!One reason for a delegate based approach is...
3 Jul 2016 by OriginalGriff
This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null -...
18 Aug 2017 by Mehdi Gholam
First don't use reflection unless you need it and you know what you are doing, so if your method counts is low use a switch statement: switch(comm.Method) { case "method1" : this.Method1(comm.Data); break; ...// and so on } You can also use a Dictionary with...
2 Jun 2020 by Richard MacCutchan
You can use them everywhere in your project. See Delegates - C# Programming Guide | Microsoft Docs[^].
26 Aug 2020 by Richard Deeming
The return type of an async function will need to be Task or ValueTask, so your delegate type will be either Func> or Func>. The function runner effectively doesn't care whether or not the function is async - it just...
23 Mar 2018 by User 7407470
For every element in the List 'list' the .NET method 'FindAll' calls the delegate method to get a value (true or false) indicating whether the value should be added to the List 'evenNumbers'. So, the .NET method 'FindAll' passes the value i to the delegate method. ...
19 Sep 2011 by Member 7835126
Hello!I'm trying to use a async Delegate to show and populate a form but the form show up and stays Not Responding.Normally the form opens OK when it's sync with the code.Example situation:Before Class:Public Delegate Sub MyAsyncDelegate()In primary sub:Dim del As...
2 Nov 2011 by HAOYE850815
Dear guys, I am currently working on a GPS tracking software. It should implement a function to trigger GPS data logging if GPS enter in a specific area and stop logging after going out of boundary.Anyway, My problem is if I select GPS as a observable object and make a GPSMonitor class...
2 Nov 2011 by Nish Nishant
Is this a typo?gpsmonitor.GeofenceOutPositioned += new GPSMonitor.PositionInGeofenceEventHandler(RaiseInEvent);gpsmonitor.GeofenceOutPositioned += new GPSMonitor.PositionInGeofenceEventHandler(RaiseOutEvent);If not, there's your bug.
19 Dec 2011 by Sergey Alexandrovich Kryukov
If looks like you have no idea how delegates work, not mentioning events and their relationship. It's hard to explain all in once, while C# and .NET manuals provides detailed explanation. First, read this: http://en.wikipedia.org/wiki/Delegation_%28programming%29[^].Start here:...
13 Apr 2012 by OriginalGriff
The easiest way is to set up a method for it: private void SetLabelText(Label l, string s) { if (InvokeRequired) { Invoke(new MethodInvoker(delegate { SetLabelText(l, s); })); } else ...
27 Aug 2012 by sinaavakh
Hello :)i want to create an array of object !i added my mywinsocket.ocx to my projectcheck this ! AxProject1.AxSocket[] Socket = new AxProject1.AxSocket[5];// load myclass private void button1_Click(object sender, EventArgs e) { for (int...
11 Aug 2013 by OriginalGriff
This Tip is intended to automate the process of adding them to your code: A Simple Code Snippet to Add an Event[^] but it provides the template for how to create and then signal an event from your user control. When you signal it to any subscribing handlers, all you do is call the "On
11 Aug 2013 by ridoy
You question is not clear enough to understand,but these will help you a lot..How to Create an Event for a User...
26 Aug 2013 by paladin_t
A Mimetic C# Style Multicast Event Implementation with C++
30 Nov 2013 by Karthik_Mahalingam
Try these linkmight be useful for you.C# Delegates, Anonymous Methods, and Lambda Expressions – O My![^]this link contians basics of lambda very informative...
24 Apr 2014 by Sergey Alexandrovich Kryukov
There is no such concept as "invoke in class". This is irrelevant. It's important in what thread you are running some code. There are two very different cases: if you need to invoke some operation to a UI thread, or to do it in some custom thread. I answered both question in detail in my past...
30 May 2014 by CHill60
ProgramFOX has solved your problem, however you may also find this CodeProject article useful - C# - Delegates 101 - A Practical Example[^]
2 Jun 2014 by CPallini
Here you are (see MSDN[^]) static void Main(string[] args) { Democlass d = new Democlass(); ExampleDelgate e1 = new ExampleDelgate(d.Add); ExampleDelgate e2 = delegate(int x, int y){ Console.WriteLine(x+y);}; // anonymous method e1(20, 10); e2(20,...
3 Dec 2014 by mccaber82
Hi,I come from a .net background and I am fairly new to developing in C++. I am building a library which carry's out low level functionality, wrapped by a C# library so it can be used in other projects.I am well used to events in C# and raising events when something meaningful happens. ...
5 Dec 2014 by KarstenK
I have added callback support to my article Calling all stations which handles now also callbacks from and into C++. Step through the code and see my solutions.
20 Jan 2016 by Richard Deeming
Seems simple enough:private bool MyCommandCanExecute(object state){ return true;}private void MyCommandExecute(object state){ // Do something...}...ICommand myCommand = new Command(MyCommandExecute, MyCommandCanExecute);
22 Mar 2016 by Patrick Skelton
Hi,I have a class which contains a function that needs to be called asynchronously at a later time. Similar to this:public class MyClass{ public Task SomeFunctionAsync() { // Do a long-running thing... }}I actually have a few of these classes, and I am...
23 Mar 2017 by Richard Deeming
Based on some crude testing, I suspect the problem is actually the other way round: you can create the delegate when the method hasn't been overridden, and you can't create the delegate when the method has been overridden.Class Foo Protected Overridable Sub Click() ...
11 Dec 2017 by phil.o
You can also do shorter: public static bool CheckisOdd(int s) { return ((s % 2) != 0); } or quicker: public static bool CheckisOdd(int s) { return ((s & 1) == 1); }
23 Apr 2018 by F-ES Sitecore
You need to tell the content page what the specific type of the master page is before you can use any public properties\methods on that master page. This can be done using the MasterType derective Working with ASP.NET Master Pages Programmatically[^] Master page has this dropdown ...
5 Jun 2018 by OriginalGriff
Please, look at your code! Why would you write this: SerialPort port = new SerialPort(); ... if (port.IsOpen) { port.Close(); port.Dispose(); } port.Open(); If it's a new port, it can't be...
7 Dec 2018 by Richard Deeming
Something like this would work: Func> factoredAreaOfCircle = factor => r => factor * Math.Pow(r, 2); Func> factoredDiameterOfCircle = factor => r => 2 * factor * r; Func iNeed = factoredDiameterOfCircle(3);...
2 Jun 2020 by OriginalGriff
To add to what Richard has said, your whole Windows app is based on delegates, though they are hidden "behind the scenes". Every time you setup, handle, or remove an event handler, that's implemented using delegates ... just you have some...
26 Jul 2020 by Member 14686752
The client is in c# and the server is in C++. Client is as follows: client.cs namespace clinetspace { public class client { [DllImport("Server.dll")] static public extern void CallServer(IntPtr obj, int a); ...
26 Aug 2020 by Patrick Skelton
I have a class that has a function that runs the supplied delegate, which is of type Func, as shown in the following code. public static class FunctionRunner { public static int RunSuppliedFunction( Func aFunctionReturningInt ) =>...
26 Aug 2020 by Patrick Skelton
With the helpful nudge from @Richard Deeming, I have got the code compiling like this (which also moves a step closer to showing what the point of all this is): public static class FunctionRunner { public static async Task...
14 Mar 2017 by User 7407470
How about this?private EventHandler _myEvent;private int _myEventSubscribersCount;public event EventHandler MyEvent{ add { _myEvent += value; _myEventSubscribersCount = _myEvent.GetInvocationList().Length; } remove { _myEvent -=...
13 Sep 2011 by TikElentrik
Hi,I have a small problem. I dont know how to convert a .net4 addhandler to .net2Can someone give me a example or a link?Or a definition of how it's named, so i can search google.The event signature don't equals the ASub signature. Dim name As String = "TikElentrik" ...
12 Sep 2011 by Richard MacCutchan
According to MSDN here[^] and here[^] the statement is the same in both versions. However, neither of them seem to match what you have coded.
12 Sep 2011 by Wayne Gaylard
There is no difference between .Net 4.0 and .Net 2.0 event handling in VB. You need to declare the method first, and ensure the event handler has the same signature as the event declaration.Try something like this:-Public Event someEvent(ByVal name As String, ByVal b As String) ...
13 Sep 2011 by TikElentrik
Thanks to the persons who tried to help me. I found a solution.Friend Class Solution Public Class SomeThing 'A bunch of stuff Public Name As String Public Sub New(ByVal Name As String) Me.Name = Name End Sub End Class Public...
9 Dec 2011 by awaisdar
i have some ques.i have understood the concept of handling the event using delegates (as some extent not whole). but there is some thing else here.Asynchronous and Synchronous Methods.1.What is the difference between the two? simple example.2. i have a method that takes 30 mint to complete,...
4 Jan 2012 by zenwalker1985
Refactoring Hooking and Unhooking Events TIP
5 Jan 2012 by Nara Har
Hello All,I have a form and I want to ensure that none of the input fields should be left blank and the txtUPrice should hold only numeric values.The below is the code that I devised.Initially when I checked for focus issues (Initial IF structure) it went fine. But when I...
6 Jan 2012 by Estys
Yes, your second "if" is messing things up.Try If x.Text = "" Then x.Focus() ErrPvdr.SetError(x, "Cannot be a blank input") ElseIf x.Name = "txtUprice" And (Not IsNumeric(x.Text)) Then x.Focus() ErrPvdr.SetError(x, "Cannot...
26 Mar 2012 by Manjunathabe011
Hi All,I have a scenario where I need to do double hop authentication. I want to Impersonate the Users in WCF service layer but want to pass the same Windows credentials of Client to DAL. My DB needs windows authentication. How can I achieve this. Thanks,Manju
5 Apr 2012 by bobishkindaguy
SOLVED - PLEASE SEE COMMENTS BELOW IF YOU ARE INTERESTED IN HOW THIS WORKED OUT, SINCE IT IS A 2-PART SOLUTION, BOTH OF WHICH ARE POTENTIALLY USEFUL TO OTHERS.Often, users will go to my program's "import data" window to initiate an import of data from a file or spreadsheet to our database....
13 Apr 2012 by Member 8404471
Hey everyone,I'm trying to send the value from a serial port via myPort.DataReceived() to a textlabel on my windows form. Error is of course, that I can't access the control from a different thread. I know i need to use invoke for that but can't get it right. I tried this:void...
4 Jul 2012 by ErickTreeTops
i'm trying to understand delegates and events and wrote a simple app based on an example.namespace DelegateTest{ public partial class Form1 : Form { BroadcastClass B = new BroadcastClass(); ListenToClass1 L1 = new ListenToClass1(); ...
4 Jul 2012 by Richard MacCutchan
I don't know where you found your example but Microsoft provide a very good one here[^].
27 Aug 2012 by Sangramsingh Pawar
Your problem is in below method private void Socket_DataIncome(object sender,AxProject1.__Socket_DataArrivalEvent e) { }This error occured due to passing wrong arguments.System.EventHandler contains below two arguments1)Object...
6 Sep 2012 by zaphoed
Passing event references as interfaces in C# by proxifying them within "EventReference" instances.
23 Dec 2012 by Sander Rossel
So I'm having a very weird problem... I'm working on a project which does some Reflection stuff. One of the things it does is read the name of methods. I've got code that, in essence, looks like the following.Public Class Form1 Private Sub Form1_Load(sender As System.Object, e As...
29 Dec 2012 by Cyberbird85
Hello everyone!I'm trying to develop an application in c# i currently have a code similar to the one attached below.Basically what it does is:Having multiple form, each of which would like to send message through the network, using my NetworkCommunicator class's SendMessage method.The...
29 Dec 2012 by Christian Graus
You can't do anything OO over the network, because you have two different exes running. You can't use delegates between two exes on two machines.
14 Jun 2013 by Michelle Phoenix
Hello,I am building a form which has various controls on it, and each control has various methods that are handled, such as onLoad, Click etc. When certain methods are fired, I need to write a log entry that that specific control's _something method was fired.However, instead of adding...
14 Jun 2013 by Mehdi Gholam
Read the following :http://msdn.microsoft.com/en-us/library/ms228976.aspx[^]http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx[^]
26 Jun 2013 by Tom Wauters
In ClassB public static void doStuffInB() { //do some really cool stuff. }in ClassA:private void Form1_Load(object sender, EventArgs e) { ClassB.doStuffInB(); }
27 Jun 2013 by Jeneesh K. Velayudhan
I have one Initialize() in my class and I am calling a delegate wrapper method from this function as follows (the call back method will call around 20 times in a sec),public Initialize(){ CX_OUTPUT_CALLBACK cb = new CX_OUTPUT_CALLBACK(OutDelegateCb); ...
26 Jun 2013 by MK-Gii
Hello Guys,I am having a hard time with passing a function name as a parameter to another function.I have the following setup:1. There are 2 classes (A and B)2. I am trying to write a function in class A which would be executing methods from class B.I know I can pass a class instance...
26 Jun 2013 by Pheonyx
Hi,I do not know if this will help, but you could use reflection to execute a method off of a class.http://stackoverflow.com/questions/2202381/reflection-how-to-invoke-method-with-parameters[^]So if you instantiate an instance of class b then use reflection to find which ever method...
11 Aug 2013 by Star135
Can anyone help me out with the code or some good link ,i am not able to find proper code for practice for raising event in user control Thanks in Advance
18 Oct 2013 by OriginalGriff
Doing the Threading stuff is pretty easy - a Background worker will handle that: BackgroundWorker work = new BackgroundWorker(); work.DoWork += new DoWorkEventHandler(work_DoWork); work.ProgressChanged += new...
29 Oct 2013 by Mohammad Sharify
Hi allI use a class to write opengl program in C++,I want to use glutDisplayFunc(display)and this my display function:void graphic::dispaly(){ glClear(GL_COLOR_BUFFER_BIT); //call a function glutSwapBuffers();}Now ,I face this error:3 IntelliSense: argument of type...
29 Oct 2013 by nv3
As Richard said, declare the display function in your graphic class as:class graphic{ ... static void display ();};and things should work.
14 Nov 2013 by Imadoddin
Hi, I have a masterpage in which I have dropdown list, I want to handle SelectedIndexChanged Event of that dropdown list in cantent page.. So far I didMasterPage:Public Event SelectedIndexChange(ByVal sender As Object, ByVal e As System.EventArgs)Public Shared Sub...
14 Nov 2013 by Jobless Creature
This Link may be of help...Save & Exit in Web Application[^]
29 Dec 2013 by Sergey Alexandrovich Kryukov
Yes, this is quite possible; and this possibility is quit often used, because big number of, for example, raw Windows API functions works through such callbacks.In this approach, a callback signature is represented by a .NET delegate type, and the actual function parameter passed to the...
30 Dec 2013 by Daniel Brousser
solved by using interfaces, thanks
10 Jan 2014 by Slavisa
Events and Delegates in Standard C++ implemented using Macro functions
27 Mar 2014 by Divakar Raj M
I am trying to interactively change button properties in the UI visually. I have a sole button in my Windows Forms application and this is my code for the button clickprivate void button1_Click(object sender, EventArgs e) { button1.BackColor = Color.Red; ...
27 May 2014 by Member 10755393
hi this vijayi have 2dropdownlist controls in usercontrols and if i selected dropdownvalues iwant to show that values in aspx textbox controls using delegates and events,iwant clear code iam new for .net
27 May 2014 by R-a-v-i-k-u-m-a-r
Try thisprotected void GetMySelection(object sender, SelectedIndexChangedEventArgs e){ TextBox1.Text= e.SelectedItem.Text;}
28 May 2014 by Rakesh Agarwal1984
public partial class _Default : System.Web.UI.Page { public delegate void mydelegate(); public event mydelegate myevent; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs...
30 May 2014 by ShaHam11
Hi I have two methods with return type one being instance and the other one is static method. I am trying to access those methods with delegates but i am unable to access it i get a error " Has wrong return typeusing System;using System.Collections.Generic;using System.Linq;using...
2 Jun 2014 by OriginalGriff
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.Try it yourself, you may find it...
24 Jul 2014 by Marisco
I'm having a tough time getting the result from my controller, it has a function that contains a delegate funciont passint as a parameter.so the result is awais empty and then goes back after its finished.HTLMName:
17 Nov 2014 by ravijmca
Basically my code is looks like below Managed.dllManaged.csclass MyManagedClass{public ShowMessage(){System.out.println("My Message");}}Wrapper.dllref class Wrapper{};Native.libclass NativeClass{public:void NativeMessage(){cout
17 Nov 2014 by KarstenK
It is an easy task. Look at this code from Microsoft.You could ofcourse use your dll and function.
4 Dec 2014 by barneyman
the easiest approach would be to write a COM object in the DLL - create an ATL simple object with a methods (say) HRESULT Register(IUnknown *eventCallback), HRESULT UnRegister(void)(don't bother with dual/dispatch, custom is fine, but make it automation safe)Use tlbimp (on the generated)...
6 Jan 2015 by Inimicos
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace delegateexample{ delegate int somedelegate(int i); class someclass { public static int somemethod(int i) { return i...
11 Nov 2015 by uddyorizu
may be signalR could help you here.As am not sure if you mean the mobile app push notifications, do forgive if its not what you need.see http://www.asp.net/signalr[^]
29 Nov 2015 by sunil kumar meena
I was trying to update status on UI for a Long Running Operating. I've created a demo form based application, task it have multiple rows, each row is having days and default values in each column of datagrid is 0, once computation file computes one iteration for one day it will update UI and set...
29 Nov 2015 by George Jonsson
I think the problem is that you when you pass the event argument, you don't pass it is a value but as a reference. See Parameter passing in C#[^]As you only create one instance of MessageEventArgs me = new MessageEventArgs();, you only have one place in the memory where your data is...
19 Jan 2016 by Patrick Skelton
Hi,I am trying to get my head around ICommand. I've done a lot of reading. Almost all of it shows the mechanics of the Command being specified using lambda syntax. I can see the value of that, but, simply to deepen my understanding, I would like to know how to write the code long-hand,...
2 Apr 2016 by Sergey Alexandrovich Kryukov
Your logic is badly, badly flawed. You start from the point where there should not be any essential difference by definition, and then, based on that, draw a conclusion that there is no difference.If you still did not get it, I'll explained on another example. This is like considering a...