Question:
what are delegates in c#?
arc
2012-06-24 10:46:46 UTC
can any one explain me what are delegates,what is the importance of delegates and what makes them so usefull in programming while calling events.ivé tried to understand the concept through many articles over the internet but the concept was not very clear to me,so plzz tell me in a way that would be simple and easy for me to understand.
Four answers:
Jonathan
2012-06-24 23:50:24 UTC
You can attempt to understand them at the "high level" most do and I think you've already struggled with web pages written by people who only understand them at that level. I think of them as creating thunks, because that is what they actually are.



Imagine a simple pointer to a function in C. It's actually a memory address that tells you where the first instruction of the function is located (if it only has one entry point, anyway, which is always the case in C.) But suppose you wanted to support nested functions in C and those nested functions could have access (scope) to the outer function's local variables. How would you implement a pointer here (assuming you only allowed a single nesting level?) A pointer in this case would require two things in order to actually call it -- the physical address of the function, of course; but now also the activation frame context of the outer function, too. In short, a call to a singly nested function requires two values in order to actually "make the call" and have it work okay. Of course, the nested function also has to be compiled properly so that it has access to its own activation frame plus the activation frame of its outer function, as well. This is the beginning of the idea of thunking. It's a different kind of function call where you have the address of the function but also the necessary context so that it has the usual access to variable instances even though its caller may not know what that is.



A delegate contains various fields in its structure. At the very least a reference to an object a pointer to some method. (Not entirely unlike having a reference to a class method and a reference to a instance of the class [the this pointer] in order that the method can be called so that it has access to the instance.) When you call a delegate, the instance method is called using the contained object reference. (Except if the object reference is NULL, then the CLR in .NET "knows" that the method must then be a static method which doesn't require access to an instance of the class.) Calling a delegate is just like calling any other function from the outside looking in, but it is quite different when you see the mechanisms actually doing their thing inside of .NET.



Delegates are a perfect fit for callback functions, for example, because they not only have the method reference so you can call the function but they also keep a reference to the necessary data for that function to operate on. Imagine calling a DLL, for example, which has it's own data instance built into it to keep its state. The caller outside of the DLL has no idea about the DLL's instance data and has no direct access to it. But to complete such a call, and before the function actually starts running its code, it must be the case that all of the "assumed pointers" are already loaded up correctly so that the DLL method will have access to the DLL instance data. Again, this is another kind of "thunk." Or "complicated function call mechanism," I suppose.



Now, as the other writer wrote here, .NET also has designed its thunking objects so that they can be chained together, as well. This means you can add a thunk to a chained list of thunks and they will all get called. But that is really a side effect benefit of having ALSO added a chaining link to the object. They would still serve their primary purpose for having been created even without chaining present. They still require everything else just in order to properly call their methods. That stuff is vital and cannot be dispensed with. But the chaining could be dumped and they would still be useful. (But contrarywise, dumping their thunking capability would make the chaining idea useless.)



I recommend studying delegates using "Accelerated C# 2010" by Trey Nash. Make sure you understand the idea of anonymous functions/lambdas. It will be a huge help in following the idea of delegates. And look up thunks and trampolines. See what you find there. (Also look up delegate combined with thunk in your search.)
Deep
2014-09-17 01:43:52 UTC
A delegate in C# is similar to function pointer in C or C++ Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.



An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method’s argument types and return type match the delegate’s. This makes delegates perfectly suited for “anonymous” invocation.



In simple terms a delegate is a data type that defines kinds of methods and explains events(which uses delegates),exception, and error handling. A delegate is a data type much similar to a class or a structure. In contrast , a delegate is a type that defines the parameters and returns values of the method.







Understanding the syntax :



The following code shows you can define a delegate type.



[accessibility] delegate returnType DelegateName ([parameters]);



Now lets break the code:



Accessibility : An accessibility for the delegate type such as public or private.



Delegate : The delegate keyword.



returnType : The data type that a method of this delegate type returns such as void , int , string.



DelegateName : The name that you want to give to the delegate.



Parameter : The paramenter list that a method of this delegate type should take.



Let’s understand this by the following example code:



The following example illustrates declaring , instantiating , and using a delegate. The class “MyFirstClass” have 2 methods Add and Length. Add simply concatenates the first name and last name of the object formed in main, and another method called Length that simply returns the length of the string entered of the first name and last name.



The delegate type used is called “MyFirstDelegate” . If we have more than one namespaces and we have classes and want to access the functionality of both the classes having same number of signatures , we can do it by using a delegate.



read complete article here : http://blog.mycampusnotes.com/working-delegates-c/
sharron
2016-07-22 08:09:38 UTC
Delegates enable you to dynamically change the behaviour of an object. That you can statically trade the behaviour of an object by using changing its type, typically to a derived category that overrides a number of approaches. However that resolution can also be too heavy weight in many situations, for instance in case you only desired to customise a sort algorithm it is simpler to pass a delegate than derive a whole new type. Altering the behaviour of an object using delegates becomes much more useful when no simplest is it impractical to derive a entire new classification for an object, you do not even know the class of the article within the first location. For instance in a consumer interface any quantity of objects is also home windows, all of so as to typically offer customisation of mouse dealing with. It's less difficult to give a delegate to the window base classification to manage the mouse than it is to derive many new classes for each type of mouse handling you would need to add. If you happen to appeared beneath the hood of C# and most an identical languages, you will in finding that virtual ways are applied using delegates.
peteams
2012-06-24 14:41:36 UTC
Delegates are equivalent to ideas like function pointers in other languages. They provide a means to represent behaviour in a variable rather than usual state, for example allowing you to pass something that says "multiply by two and add three" rather then just "7".



You could replicate all (or most of) the features of a delegate by having a class with a virtual function. So rather than passing the delegate you would pass an instance of the object. However that involves defining a new class and all the code that goes with it, the overhead of which is likely to be far more error prone than being allowed to just pass the function.



Consider two typical uses, sorting and user interfaces.



You can specify a sort function as something that takes an array and a comparison function and applies the comparison function in an appropriate manner, moving members around in the array as appropriate. Having delegates allows you to provide the comparison function that defines the order.



More commonly encountered is their use in user interfaces. A page, form or generalised bit of user interface will consist of controls supplied by the environment. These controls will have behaviours, buttons that push, test boxes that edit and so on. In order to make a useful user interface some of these behaviours need to be modified, so clicking the OK button closes the form for example.



For each special bit of user interface behaviour you could derive the appropriate control from the original default control. But that would be incredibly time consuming and error prone. Moreover user interfaces normally consist of a layout portion designed by a user interface person and a functional part written by a programmer, using specialised controls implies a tight coupling between the two parts.



Delegates allow you to attach a Click behaviour to an OK button without the button being anything other than a standard button.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...