Click here to Skip to main content
15,888,401 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 Title

Delegates 

30 Nov 2013 by agent_kruger
i would like to know the concept of Delegates and lambda.Example code will be appriciated. Thanks In Advance.
30 Nov 2013 by OriginalGriff
If you have "refered many google links" then what do you expect us to tell you that you haven't found? Especially in a little textbox like this?Go back to Google, and look again: it contains a huge amount of information on the subject which will better answer a general question such as this.
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...
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...
7 Dec 2012 by Rahul Rajat Singh
This article discusses delegates and how to write delegate handlers using functions, anonymous functions and Lambda expressions.
26 Aug 2013 by paladin_t
A Mimetic C# Style Multicast Event Implementation with C++
7 Dec 2018 by C Pottinger
Hello Code Project Gurus I know it is possible to have delegates operate with values that are known at the time the delegate is called - that's simply a parameter e.g. Func areaOfCircle = r => Math.PI * Math.Pow(r, 2); Func diameterOfCircle = r => 2 *...
6 Dec 2018 by Dave Kreskowiak
You cannot change the delegate definition at runtime. A delegate is nothing but a pointer to a function. The parameter list of the delegate must match the parameter list of the function that it points to. If it doesn't you can unbalance the stack as the call is pushing parameters on the stack...
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 2014 by ShaHam11
Hi , Can some one help me to convert this Delegate program method to anonymous method using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Delgates_Ex1{ public delegate void ExampleDelgate(int x, int y); class Democlass ...
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,...
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...
19 Dec 2022 by David Lafreniere
A C++ standards compliant delegate library capable of targeting any callable function synchronously or asynchronously
19 Dec 2022 by David Lafreniere
A C++17 standards compliant delegate library capable of targeting any callable function synchronously or asynchronously
12 Nov 2013 by John Pravin
Asynchronous Programming with Task Parallel Library.
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....
5 Apr 2012 by Pablo Aliskevicius
I've done something similar in the past.I noticed this:Events can happen hundreds of times per second, but users don't read that fast.A process can send thousands of updates to the progress form, but a progress bar won't be more than a few hundred pixels wide.Drawing is...
10 Sep 2014 by DiponRoy
Let's make a lambda expression from a property name of a particular entity, and use it for OrderBy shorting
22 Aug 2013 by YourAverageCoder
Hi, i have a problem with following declaration:T Single ( Expression > expression, params Expression >[] includes ) where T : class;Now i get it that T is a generic type but what i don't get are the "Expression" and "params" data types. Googling...
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...
26 Mar 2017 by Danilow
Simulating C# event handlers in Java
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.
20 May 2012 by cpsglauco
How to use delegate in List.Find() predicate in C#
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.
23 Mar 2018 by The_Unknown_Member
I'm reading a book and I have problems understanding this code: List evenNumbers = list.FindAll(delegate(int i) { return (i % 2) == 0; }; I cannot understand what will happen with this code. Who passes the argument to the parameter i and how? I'm really confused. What I have...
23 Mar 2018 by #realJSOP
Google is your friend. Anonymous Functions (C# Programming Guide) | Microsoft Docs[^]
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. ...
4 Feb 2019 by Timothy Hogan
In my embedded program I have a 5 "soft keys" arranged with a LCD screen. What I would like is to have a pointer for each button that can point to free functions or member functions and can take any signature. This pointer will need to be redirected to other functions at runtime. Obviously I...
4 Feb 2019 by Richard MacCutchan
There is no easy way around this, since the compiler needs to check the call matches the function signature. You could define each function to take a void* as its only parameter and then cast it internally to the correct structure. Or you could use the varargs option where you pass one fixed...
4 Feb 2019 by CPallini
As far as know, without considering 'dirty hacks' (trying to defeat the strongly typed nature of C++), you cannot do that. I would use just one function signature and then adapt all of my functions to comply with it. Within this approach you might possibly find useful std::function[^].
17 Aug 2023 by hans.sch
I'm playing with C++/CLI and calling into a .NET assembly. There is no specific use case, I simply want to learn. I wrote the assembly in C#. It exports a class with a few methods, and a delegate type which is used in one of the methods:...
18 Aug 2023 by Maxim Kartavenkov
had you try the next way: int MyCallback(int i) {} public delegate int IntCallback(int i); IntCallback^ callback = gcnew IntCallback(MyCallback); // Use callback variable as an argument
1 Dec 2017 by Jon McKee
How to do it and why it works
2 May 2012 by Ramana Bellary
I have two projects Project1 and Project2. I have refernce of Project2 in Project1.I have declared a Delegate in Project2 and on click of button I am invoking the Delegate.Project2 - Form2 Code :Public Delegate Sub ExternalDelegate()Public Class Form2 Public Event Del As...
19 Aug 2017 by MYQueries1
I am using the Invoke method to call method using reflection. Performance of this not great. Is there any other solution What I have tried: void ExecuteMethodViaReflection(TestObj comm) { var paramNames = comm.paramNames; //of type string array var paramData = comm.Data; //of type...
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...
19 Aug 2017 by Graeme_Grant
Expanding on Mehdi Gholam's solution, here is a real-life example of where the method ProcessFileType "discovers" the type of data that it needs to convert to, looks up the type of data, then executes the conversion from JSON string and returns a class structure of a specific type. // only some...
23 Jul 2012 by Shabbir Lathsaheb
Another useful feature of delegates is the ability to execute a method asynchronously. That is, through a delegate, you can begin invocation of a method and then return immediately while the delegate executes its method in a separate thread.
23 Jan 2018 by Ammar Shaukat
I'm working on a software where software issues commands for hardware panel and once a command is issued, its response received after few seconds . there are different functions for different hardware commands like public void FunctionA() { StartCommandA(); } and other functions on the...
23 Jan 2018 by johannesnestler
have a look at the Task class Task Class (System.Threading.Tasks)[^] and to the ContinueWith methods. This is what you want: call methods each in it's own Task (thread) - wait for method to execute while not blocking the rest of your app. After executing continue with next method call (in it's...
23 Jan 2018 by Ammar Shaukat
Make a list of Action Delegates and add Status Code for each function . let's say 0 mean function has invoked and 1 mean function is not invoked yet. then use LINQ Query to check which function has called and which one is remaining. Change the status of function invocation from OnReponse ...
31 Oct 2015 by petarpetrovt
class Foo{ [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")] private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); public delegate void TestMethod(uint cap); public static TestMethod Method; static Foo() { Method =...
31 Oct 2015 by phil.o
delegate void EnclosingDelegate(string parameter);delegate string EnclosedDelegate();class foo{ void main() { EnclosedDelegate enclosed = () => "foo"; EnclosingDelegate enclosing = (s) => s = enclosed(); }}Is that what you are searching for?
11 Dec 2017 by dhivya N
I am a new learner of c#. I want to find a number is odd or not using delegate anonymous function. I am getting the the above error. Where am i going wrong? What I have tried: public delegate bool oddOREvenDelegate(int s); class Program { static void Main(string[] args) ...
11 Dec 2017 by ________________
You do not need to create delegate twice: public static bool CheckisOdd(int s) { if (s % 2 == 0) { return false; } else { return true; } }
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); }
11 Dec 2017 by George Swan
public static void Main (string[] args) { //define a delegate that takes an int and returns a bool Predicate CheckIsOdd=i=>i%2!=0; //call the delegate and write the result Console.WriteLine(CheckIsOdd(5)); //An alternative approach using an anonymous function...
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 Mar 2014 by Raul Iloc
You should invoke button1.Refresh() after each change of color, but before Thread.Sleeep()!
27 Mar 2014 by OriginalGriff
Simple: don't use Sleep at all.Sleep suspends the current thread, so it does absolutely nothing until the time period has expired. Since it is the UI thread (or you wouldn't be in the Click event handler) that means that the thread that updates the display is suspended - so the display won't...
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...
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...
23 Mar 2017 by Ralf Meier
My Situation is that I want to have a Delegate to a method from a Control.For that I use the code as follows : Private RepeatDelayCounter As Integer = 0 Private RepeatControl As Control = Nothing Private Delegate Sub delegate_OnClick(instance As Control, e As...
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() ...
23 Jul 2012 by PratapReddyP
In this post, we will go back to basics of C# concepts. From the time when i am new to .Net development till today, one of the first five C# questions is" What is a Delegate? What is an Event? What are the Differences? "
8 Nov 2014 by Mahdi K.
A detailed description for Delegate, Func, Predicate, Action and Lambda Expression.
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[^].
15 May 2020 by MAU787
hi alli have one application which calls one function from dll.that dll invokes one delegate for capturing fingerprint.but after 4-5 capture i m getting error..A callback was made on a garbage collected delegate of type...
15 May 2020 by martonthenagy
This may be useful for You: .net - Call has been made on garbage collected delegate in C#? - Stack Overflow[^]
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...
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) { /*...
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...
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 CHill60
ProgramFOX has solved your problem, however you may also find this CodeProject article useful - C# - Delegates 101 - A Practical Example[^]
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
15 May 2012 by abhinav_soni
Support for Delegates, Events and Pass by ref in Java using bytecode manipulation
1 Dec 2015 by Shivprasad koirala
In this article we will try to understand Delegates, Multicast delegates and Events in C#
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...
20 Oct 2013 by Member 8392278
Does anyone have a simple way of making this TreeView WinForm app multithreaded – the UI locks up. I have experimented with the backgroundworker , treeview.invoke and delegates but need help in these areas. Thank you in advance for any assistance.
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...
8 Nov 2015 by DotNetSteve
Using delegates to group, conquer cross cutting concerns and create dynamic validators
8 Nov 2015 by DotNetSteve
Using delegates to group, conquer cross cutting concerns and created dynamic validators
30 May 2017 by n.podbielski
Explanation how to convert from one delegate type to second delegate of unknown or dynamically created type when their signatures match.
28 Jun 2013 by Jeneesh K. Velayudhan
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); ...
27 Jun 2013 by Ron Beyer
public Initialize(){ CX_OUTPUT_CALLBACK cb = new CX_OUTPUT_CALLBACK(OutDelegateCb); AureusSDK_Wrapper_VideoCallbackFunSetup.CX_SetOuputCallBack(cb, cnt); GC.KeepAlive(cb);} public static void OutDelegateCb(IntPtr p_aureus_video_output,...
10 Jan 2014 by Slavisa
Events and Delegates in Standard C++ implemented using Macro functions
30 Aug 2013 by Dev Leader
Let’s see how events might be causing some leakage in your application.
15 Jan 2015 by Bhushan Mulmule
This write-up will take you through all the steps that are required to understand lambda expression thoroughly.
5 Mar 2017 by DotNetSteve
Creating an extension class for View Models to save public properties using Generics and Delegates, replacing a reflection implementation
14 Jan 2020 by yutaraa
Get, move, copy and delete event handler delegates of Windows form controls.
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...
6 Oct 2021 by dotarsoyak
Hello I have an implementation of Flutter Navigator 2.0 in my app, wich one has a SearchDelegate implemented too, but when I do tap on the search box search button, my app launch an error, the console prints this message: I think I have a bad...
19 Oct 2014 by Nikita Mazhara
Describes how to implement generic methods for Microsoft Fakes Stubs and Shims using reflection constructed delegates at runtime
3 Nov 2015 by Ayesha_K
Somebody suggested me to do it with Jquery . I don't know where to start from but the scenario is that I need an online shopping store website,in which on clicking on 'ORDERNOW" button on "Add to cart"'s window ,the notification is pushed on admin panel which tells about that particular order's...
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[^]
21 May 2016 by Abtin Bina
i have an object that it have a 'Thread' property like this class Client{ public Thread ClientThread; // it is that i want to change //some property //some method }how can i set the ClientThread in a started threadlike what i have triedWhat I have...
21 May 2016 by Sergey Alexandrovich Kryukov
You can find some useful ideas in my past answers:http://www.codeproject.com/Answers/536542/anplusamateurplusquestionplusinplussocketplusprogr#answer2[^],http://www.codeproject.com/Answers/165297/Multple-clients-from-same-port-Number#answer1[^],specifically on the problem of disconnection:...
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 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...
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...
24 Apr 2014 by nazarinlaw
Hello everyone, im really sorry if i did anything wrong, i just don't know how to make this thing works ! So everyone here's the class i made it to store the logs into TextBox / txt.Public Class EventLogger#Region " Events " Public Event EntryWritten As...
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...
14 Mar 2017 by Patrick Skelton
If I use the explicit syntax for declaring an event, is it possible to get the number of subscribers inside the add {} and remove {} code blocks? For example:public event EventHandler MyEvent{ add { MyEvent += value; // Can I get a count of subscribers here? ...