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 Updated

Delegates 

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
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:...
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
16 Dec 2021 by Eugene Rutsito
I have four (4) class libraries in c#. Three (3) (InitiatorModule, TransactorModule, LoggerModule) of which are higher level and one (1) (PublisherModule) is a lower level. All the three higher level projects have project reference to the lower...
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...
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...
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 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); ...
25 Jul 2020 by Shao Voon Wong
The C# client can do polling. While polling is easy to do, it is inefficient and a waste of CPU cycles. C++ server can create event(CreateEvent[^]) and signal the event handle whatever there is data to be received. C# client will create object...
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...
2 Jun 2020 by Gauravg9598
I want to know that where delegate in c# has been used in Dot Net Projects. How we can used delegate in Dot Net Projects. How to that in project where we use delegate What I have tried: I want to know that where delegate in c# has been used in...
2 Jun 2020 by Richard MacCutchan
You can use them everywhere in your project. See Delegates - C# Programming Guide | Microsoft Docs[^].
15 May 2020 by martonthenagy
This may be useful for You: .net - Call has been made on garbage collected delegate in C#? - Stack Overflow[^]
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...
14 Jan 2020 by yutaraa
Get, move, copy and delete event handler delegates of Windows form controls.
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 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[^].
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...
31 Jan 2019 by pdoxtader
Setting up a function on your form that does the work of switching to the UI thread and updating the UI for you is not a bad idea, but setting up multiple functions to update individual controls isn't necessary. You can pass your function an action delegate instead, and then use the same...
31 Jan 2019 by Sonhospa
Hello, I made a small sample project in order to learn the use of a delegate to update the UI (older way / pre-Net4.0). I have no idea what might be wrong, since the UI is sometimes updating and sometimes not - but never in the expected way of counting upwards (visible), only the result is...
31 Jan 2019 by raddevus
You are using the UI thread even though it seems as if you are new'ing up a new thread. So when you sleep the thread you are actually sleeping the main UI thread. Invoke used like this is rarely the way to go. It is quite a bit easier to do this via BackgroundThreadWorker which you can assign...
16 Dec 2018 by TheBigBearNow
Hello all, I am trying to use a backgroundworker and I want to invoke a delegate to get my loadingspinner to run while I am running a query. How would I do this? Here is code I have? public LoginScreen() { InitializeComponent(); backgroundWorker = new...
16 Dec 2018 by Graeme_Grant
The UI runs in the main thread, so you can't access the UI from a different thread. So you have a flag that the Spinner Visibility is bound to using data binding, say is called IsBusy. Then you communicate to the UI via the flag. Secondly, as OriginalGriff mentioned, you then offload the...
16 Dec 2018 by OriginalGriff
Do it the other way round: display the spinner - and control it - from the main UI thread, and use the BackgroundWorker events to monitor progress and termination. The long job gets done in the BackgroundWorker, the UI in the UI thread. That way, there is no need to invoke anything! (That's...
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 *...
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);...
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...
6 Jun 2018 by Richard Deeming
Quote: port.DataReceived += new SerialDataReceivedEventHandler(new cEventHandler().DataReceivedHandler); port.DataReceived -= new SerialDataReceivedEventHandler(new cEventHandler().DataReceivedHandler); You've added two handlers to the event. Therefore, every time the event is raised, your...
6 Jun 2018 by Nishikant Tayade
First I am subscribing to an event and then in the method which will be executed when that event occurs i am unsubscribing it.But still I think it is getting fired many times. What I have tried: using System; using System.Collections.Generic; using System.IO; using System.IO.Ports; using...
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...
5 Jun 2018 by Chander Parkash Mourya
DataReceived event should be subscribed before calling Open() method of SerialPort class. As per your result event is called many times- In my case event will be called only in case of any response comes from another paired port. For ex. Paired ports are - "COM5" "COM3" so when any...
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 ...
22 Apr 2018 by helpwithmycode
INFORMATIVE BACKGROUND: I have a ddl control in master site, i would like to call the 'selectIndexChange event' that sits in master page, and i want to call it in a content page. the reason is because i have an adio.net function that populates a grid in my content page. when i select a new item...
5 Apr 2018 by Member 1960377
I am working on a window application (written using Vb.net).In the main form Load event another form 'frmcrew_managment' is also loaded.In this stage for RefreshClick event of Main form attaches 'Refreshadata' method ( handler) of 'frmcrew_managment' . As a result after the main form is loaded...
23 Mar 2018 by OriginalGriff
Quote: EDIT: Oooooh. It's the signature... Sorry for the stupid question........ It is indeed! For the benefit of others with a similar problem, the sh2 declaration requires a parameter: ReturnAStringHandler sh = ReturnAString; ReturnAStringHandler sh2 = (x) => sh(x); ...
23 Mar 2018 by The_Unknown_Member
What's the problem with the following code? class Program { public delegate string ReturnAStringHandler(string s); static void Main(string[] args) { ReturnAStringHandler sh = ReturnAString; ReturnAStringHandler sh2 = () => sh("Hello"); ...
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. ...
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 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 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 ...
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...
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 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...
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 ________________
You do not need to create delegate twice: public static bool CheckisOdd(int s) { if (s % 2 == 0) { return false; } else { return true; } }
1 Dec 2017 by Jon McKee
How to do it and why it works
4 Oct 2017 by İsmail Fatih ILTAR
Hi, i have to write C# class and method from C codes. My C codes are below. function_ex takes function pointer which takes custom_pac_type_t pointer.Problem is about method declaration. i can't use Func cause there is a ref parameter. I must use delegates but i couldnt. How can i pass func...
4 Oct 2017 by Richard MacCutchan
See Delegates (C# Programming Guide) | Microsoft Docs[^]
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...
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...
17 Jun 2017 by rashiqkt
I have an application in wpf where I use UserControl to fill some data.I need some actions performed in the parent window while clicking on a button in UserControl. I tried using events and delegates but failed to call the function in parent window. What I have tried: in my usercontrol I have...
17 Jun 2017 by OriginalGriff
Just add an event and then get the container form to handle it: A Simple Code Snippet to Add an Event[^] - it shows the code you need, and how to "automate it" in VS.
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.
26 Mar 2017 by Danilow
Simulating C# event handlers in Java
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() ...
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? ...
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 -=...
14 Mar 2017 by OriginalGriff
You can only do it from within the class that creates the event: public class MyClass { public event EventHandler MyEvent; protected virtual void OnMyEvent(EventArgs e) { EventHandler eh = MyEvent; ...
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.
5 Mar 2017 by DotNetSteve
Creating an extension class for View Models to save public properties using Generics and Delegates, replacing a reflection implementation
18 Jan 2017 by Doug Langston
A Visual Studio 2015 project that shows one way to pass information between Windows Forms
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.
8 Dec 2016 by Patrick Skelton
I have been trying to follow the article here Crafting Task Timeout on how to create a utility extension method to add a timeout to a Task.My code (with some omissions) is shown below. It shows two versions of the timeout functionality, one non-generic and one generic.As you can see, I...
4 Oct 2016 by BillW33
As _duDE_ said, if you send data packets asynchronously there is no way to know the order in which they will be received. What you have to do on the receiving end is to reassemble the packets into the correct order. To do this they must be sent with some field that indicates the correct order....
4 Oct 2016 by Member 7754814
Hi,I am facing issue while consuming data in event in window application. Data received is not in same sequence as sent from class where event is raised. Here is complete scenario.There are 2 threads. In one thread, I receive data packets over TCP continuously and put it in array. In other...
4 Oct 2016 by Leo Chapiro
If you send and receive the data asynchronous, there is no guarantee to get this data in the same sequence as sent.
12 Jul 2016 by Anisuzzaman Sumon
Dear Experts,Just let me know is the following code executed as asynchronously ?My Code is shown belowpublic class CompanyController : Controller {public delegate void CompanyAuditRecordKeeper(CompanyModel company, string operationType); public ActionResult Create(CompanyModel...
12 Jul 2016 by OriginalGriff
The short answer is "maybe".The official documentation says: Executes the specified delegate asynchronously with the specified argumentswhich is pretty clear!But... It goes on to say:on the thread that the control's underlying handle was created on.Which means that it does get executed...
11 Jul 2016 by Alberto Nuti
In a console application, there is often the need to ask (and validate) some data from users. For this reason, I have created a function that makes use of generics and delegates to speed up programming.
3 Jul 2016 by Prakash1206
I'm new to Dock Panel suiteBasically i'm having run time error when it comes to loading layout from xml file. saving layout works fine.I have 2 forms, 1st one is main form. 2nd form is child formpublic ref class MyForm2 : DockContent //2nd form (child form)in main form, i have following...
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 -...
30 May 2016 by Member 12555296
I have create a small class CountDown , that contains a timer.Class is very simple : receive time target, and start a CountDown with a timer.When target is reached, my personal event fireusing System;using System.Collections.Generic;using System.Linq;using System.Text;using...
30 May 2016 by Sergey Alexandrovich Kryukov
Main wrong thing here is using System.Windows.Forms. You cannot expect anything good from this kind of a timer. As far as I can see, you need more or less periodic behavior, to see how the label shows count down time. With this timer, don't even dream about it, even if sometimes you got an...
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:...
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...
5 Apr 2016 by Patrick Skelton
I am not sure if it is the only or best solution, but the following code achieves what I was looking to do. Basically, all I have done is changed the "dumb" integer _count variable to a class, which means it is passed by reference and it can maintain its own internal state, like this:using...
5 Apr 2016 by Patrick Skelton
Hi,I am a little confused by the System.Threading.Timer class. The following code compiles and runs fine:using System;using System.Threading;namespace ConsoleApplication1{ public class Repeater { public Repeater( Action callback, object state ) { // Timer...
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...
2 Apr 2016 by Member 9346617
lets' say I have 2 buttons. Add & Substract.I will write two seperate functions "Add" & "Substract" & i will call them accordingly on each button click.Then why should I go for delegate when things are already known to me in advance which function to call on which button click ?What 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...
22 Mar 2016 by Richard Deeming
If you store the results in a List, the methods will be invoked once, and you will be able to retrieve the results from the list.If you want to invoke the methods multiple times on demand, store them in a List>:var listOfDelegates = new List>{ ...
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...
22 Mar 2016 by Rakesh Meel
visit Here to understand....Asynchronous Method Invocation[^]
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);
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,...
1 Dec 2015 by Shivprasad koirala
In this article we will try to understand Delegates, Multicast delegates and Events in C#
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...
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...
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[^]
8 Nov 2015 by DotNetSteve
Using delegates to group, conquer cross cutting concerns and created dynamic validators
8 Nov 2015 by DotNetSteve
Using delegates to group, conquer cross cutting concerns and create dynamic validators
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...
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?
25 Aug 2015 by K. Naveen. Bhat
The article shows how we can solve various technical problems easily with the help of delegates.