What is delegate in C#? [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
I am a beginner of C#, and I can't understand delegate.
Can anybody provide me some better links through which I can understand quickly?

Explaining delegates with adequate details id beyond the scope of this answer. I'd point you to few articles that can help you understand this.
http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx
http://msdn.microsoft.com/en-us/library/aa288459(VS.71).aspx
From MSDN..
A delegate in C# is similar to a
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.
A delegate declaration defines a type that encapsulates a method with a particular set of arguments and return type. For static methods, a delegate object encapsulates the method to be called. For instance methods, a delegate object encapsulates both an instance and a method on the instance. If you have a delegate object and an appropriate set of arguments, you can invoke the delegate with the arguments.
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.

Have you checked out the MSDN:
delegate:
A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure.
An Introduction to Delegates, the first sentence of which states:
Callback functions are certainly one of the most useful programming mechanisms ever created.
So, if you are familiar with callbacks, you have some understanding of delegates already.

Related

C# callback requires object to be referenced as UInt32? [duplicate]

This question already has answers here:
What is void* in C#? [duplicate]
(7 answers)
Closed 6 years ago.
I need to be able to pass a context object when i register a call back using the following method, which is linked to a C++ DLL file so cant change the method parameters. The callback returns this as one of the arguments when the callback method is executed.
public static void RegisterCallback(UInt32 instance, CALLBACK callbackFunction, UInt32 context)
The last argument is the only one I'm having trouble with. I'm assuming that its meant to be the memory address (or a reference) of the object.
The C++ code has this argument as void*
Any ideas?
This is very common in a C-style api that permits registering a callback. It plays the exact same role as, say, IAsyncResult.AsyncState in managed code for example. The callback gets the value back, it can use it for any purpose it likes. Could be an index in an array of objects for example. Could be a state variable. In the case of C++, it very commonly is the this pointer of the C++ object. Very handy, permits calling an instance function of the C++ object. Anything goes.
Do note that it is pretty unlikely that you need it. First hint that you don't is that you just don't know what to use it for. And that's pretty likely in C# because you already have context. The delegate you use for the callbackFunction argument already captures the this object reference. So any state you need in the callback method can already be provided by fields of the class. Just like C++, minus the extra call.
So don't worry about it, pass 0. Or really, fix the declaration, the parameter should be IntPtr, pass IntPtr.Zero. Probably also what you should do for the instance argument, it quacks like a "handle". A pointer under the hood.
And be careful with the callbackFunction argument, you need to make sure that the garbage collector does not destroy the delegate object. It does not know that the native code is using it. You have to store it in a static variable or call GCHandle.Alloc() so it is always referenced.

Why does the .NET framework specify standard delegates (Action)?

Why does the .NET framework specify standard delegates? Declaring a new delegate type is simple and can be done in one line of code.
public delegate void Something<T>(T obj);
Why do they define all these other types (Action, Action, etc.)?
What is the purpose and what was to be gained by this?
http://msdn.microsoft.com/en-us/library/system.action.aspx
Another thing that I wonder about is that they then go on to define 17 versions that are all the same except they take different numbers of type parameters. But why stop at 17? What informs that type of decision?
Because they wanted to expose some delegate definitely for the TPL as well as Linq, so they created Action, Action<T> and Func<> delegates.
Enumerable class uses Func<> in number of methods.
Task class was built on top of Func<> as well as Action<> delegates only.
When they expose the Linq in FW it is necessary to declare the delegates like Predicate kind of delegate which should operate with Where clauses and so forth. You can declare your own delegate in single line. but the point is you can't pass your delegate to framework method, since framework don't have your delegate at compile time.
So framework developers decided to add these standard delegates in the .Net framework itself.
Note:You could pass your own delegates to "BCL" types as System.Delegate type and they can use DynamicInvoke method to invoke it but that is an overkill. It requires boxing/unboxing when dealing with "ValueTypes" that degrades the performance, not only that DynamicInvoke itself poor performing candidate.
If one piece of code declares:
public delegate void SingleArgumentMethod<T>(T obj);
DoSomething(SingleArgumentMethod<int> thingDoDo);
and some other code declares:
public delegate void OneArgumentMethod<T>(T obj);
PerformAction(OneArgumentMethod<int> theAction);
then because SingleArgumentMethod<int> and a OneArgumentMethod<int> will be unrelated types, there will be no nice way for DoSomething to pass its received delegate to PerformAction. Instead it will have to produce an instance of OneArgumentMethod<int> using the method pointer(s) and target(s) from thingToDo, and pass that to PerformAction. If, however, both methods had used same delegate definition, such complication wouldn't be necessary and DoSomething could simply call PerformAction(thingToDo);.

Why are delegates reference types?

Quick note on the accepted answer: I disagree with a small part of Jeffrey's answer, namely the point that since Delegate had to be a reference type, it follows that all delegates are reference types. (It simply isn't true that a multi-level inheritance chain rules out value types; all enum types, for example, inherit from System.Enum, which in turn inherits from System.ValueType, which inherits from System.Object, all reference types.) However I think the fact that, fundamentally, all delegates in fact inherit not just from Delegate but from MulticastDelegate is the critical realization here. As Raymond points out in a comment to his answer, once you've committed to supporting multiple subscribers, there's really no point in not using a reference type for the delegate itself, given the need for an array somewhere.
See update at bottom.
It has always seemed strange to me that if I do this:
Action foo = obj.Foo;
I am creating a new Action object, every time. I'm sure the cost is minimal, but it involves allocation of memory to later be garbage collected.
Given that delegates are inherently themselves immutable, I wonder why they couldn't be value types? Then a line of code like the one above would incur nothing more than a simple assignment to a memory address on the stack*.
Even considering anonymous functions, it seems (to me) this would work. Consider the following simple example.
Action foo = () => { obj.Foo(); };
In this case foo does constitute a closure, yes. And in many cases, I imagine this does require an actual reference type (such as when local variables are closed over and are modified within the closure). But in some cases, it shouldn't. For instance in the above case, it seems that a type to support the closure could look like this: I take back my original point about this. The below really does need to be a reference type (or: it doesn't need to be, but if it's a struct it's just going to get boxed anyway). So, disregard the below code example. I leave it only to provide context for answers the specfically mention it.
struct CompilerGenerated
{
Obj obj;
public CompilerGenerated(Obj obj)
{
this.obj = obj;
}
public void CallFoo()
{
obj.Foo();
}
}
// ...elsewhere...
// This would not require any long-term memory allocation
// if Action were a value type, since CompilerGenerated
// is also a value type.
Action foo = new CompilerGenerated(obj).CallFoo;
Does this question make sense? As I see it, there are two possible explanations:
Implementing delegates properly as value types would have required additional work/complexity, since support for things like closures that do modify values of local variables would have required compiler-generated reference types anyway.
There are some other reasons why, under the hood, delegates simply can't be implemented as value types.
In the end, I'm not losing any sleep over this; it's just something I've been curious about for a little while.
Update: In response to Ani's comment, I see why the CompilerGenerated type in my above example might as well be a reference type, since if a delegate is going to comprise a function pointer and an object pointer it'll need a reference type anyway (at least for anonymous functions using closures, since even if you introduced an additional generic type parameter—e.g., Action<TCaller>—this wouldn't cover types that can't be named!). However, all this does is kind of make me regret bringing the question of compiler-generated types for closures into the discussion at all! My main question is about delegates, i.e., the thing with the function pointer and the object pointer. It still seems to me that could be a value type.
In other words, even if this...
Action foo = () => { obj.Foo(); };
...requires the creation of one reference type object (to support the closure, and give the delegate something to reference), why does it require the creation of two (the closure-supporting object plus the Action delegate)?
*Yes, yes, implementation detail, I know! All I really mean is short-term memory storage.
The question boils down to this: the CLI (Common Language Infrastructure) specification says that delegates are reference types. Why is this so?
One reason is clearly visible in the .NET Framework today. In the original design, there were two kinds of delegates: normal delegates and "multicast" delegates, which could have more than one target in their invocation list. The MulticastDelegate class inherits from Delegate. Since you can't inherit from a value type, Delegate had to be a reference type.
In the end, all actual delegates ended up being multicast delegates, but at that stage in the process, it was too late to merge the two classes. See this blog post about this exact topic:
We abandoned the distinction between Delegate and MulticastDelegate
towards the end of V1. At that time, it would have been a massive
change to merge the two classes so we didn’t do so. You should
pretend that they are merged and that only MulticastDelegate exists.
In addition, delegates currently have 4-6 fields, all pointers. 16 bytes is usually considered the upper bound where saving memory still wins out over extra copying. A 64-bit MulticastDelegate takes up 48 bytes. Given this, and the fact that they were using inheritance suggests that a class was the natural choice.
There is only one reason that Delegate needs to be a class, but it's a big one: while a delegate could be small enough to allow efficient storage as a value type (8 bytes on 32-bit systems, or 16 bytes on 64-bit systems), there's no way it could be small enough to efficiently guarantee if one thread attempts to write a delegate while another thread attempts to execute it, the latter thread wouldn't end up either invoking the old method on the new target, or the new method on the old target. Allowing such a thing to occur would be a major security hole. Having delegates be reference types avoids this risk.
Actually, even better than having delegates be structure types would be having them be interfaces. Creating a closure requires creating two heap objects: a compiler-generated object to hold any closed-over variables, and a delegate to invoke the proper method on that object. If delegates were interfaces, the object which held the closed-over variables could itself be used as the delegate, with no other object required.
Imagine if delegates were value types.
public delegate void Notify();
void SignalTwice(Notify notify) { notify(); notify(); }
int counter = 0;
Notify handler = () => { counter++; }
SignalTwice(handler);
System.Console.WriteLine(counter); // what should this print?
Per your proposal, this would internally be converted to
struct CompilerGenerated
{
int counter = 0;
public Execute() { ++counter; }
};
Notify handler = new CompilerGenerated();
SignalTwice(handler);
System.Console.WriteLine(counter); // what should this print?
If delegate were a value type, then SignalEvent would get a copy of handler, which means that a brand new CompilerGenerated would be created (a copy of handler) and passed to SignalEvent. SignalTwice would execute the delegate twice, which increments the counter twice in the copy. And then SignalTwice returns, and the function prints 0, because the original was not modified.
Here's an uninformed guess:
If delegates were implemented as value-types, instances would be very expensive to copy around since a delegate-instance is relatively heavy. Perhaps MS felt it would be safer to design them as immutable reference types - copying machine-word sized references to instances are relatively cheap.
A delegate instance needs, at the very least:
An object reference (the "this" reference for the wrapped method if it is an instance method).
A pointer to the wrapped function.
A reference to the object containing the multicast invocation list. Note that a delegate-type should support, by design, multicast using the same delegate type.
Let's assume that value-type delegates were implemented in a similar manner to the current reference-type implementation (this is perhaps somewhat unreasonable; a different design may well have been chosen to keep the size down) to illustrate. Using Reflector, here are the fields required in a delegate instance:
System.Delegate: _methodBase, _methodPtr, _methodPtrAux, _target
System.MulticastDelegate: _invocationCount, _invocationList
If implemented as a struct (no object header), these would add up to 24 bytes on x86 and 48 bytes on x64, which is massive for a struct.
On another note, I want to ask how, in your proposed design, making the CompilerGenerated closure-type a struct helps in any way. Where would the created delegate's object pointer point to? Leaving the closure type instance on the stack without proper escape analysis would be extremely risky business.
I can tell that making delegates as reference types is definitely a bad design choice. They could be value types and still support multi-cast delegates.
Imagine that Delegate is a struct composed of, let's say:
object target;
pointer to the method
It can be a struct, right?
The boxing will only occur if the target is a struct (but the delegate itself will not be boxed).
You may think it will not support MultiCastDelegate, but then we can:
Create a new object that will hold the array of normal delegates.
Return a Delegate (as struct) to that new object, which will implement Invoke iterating over all its values and calling Invoke on them.
So, for normal delegates, that are never going to call two or more handlers, it could work as a struct.
Unfortunately, that is not going to change in .Net.
As a side note, variance does not requires the Delegate to be reference types. The parameters of the delegate should be reference types. After all, if you pass a string were an object is required (for input, not ref or out), then no cast is needed, as string is already an object.
I saw this interesting conversation on the Internet:
Immutable doesn't mean it has to be a value type. And something that
is a value type is not required to be immutable. The two often go
hand-in-hand, but they are not actually the same thing, and there are
in fact counter-examples of each in the .NET Framework (the String
class, for example).
And the answer:
The difference being that while immutable reference types are
reasonably common and perfectly reasonable, making value types mutable
is almost always a bad idea, and can result in some very confusing
behaviour!
Taken from here
So, in my opinion the decision was made by language usability aspects, and not by compiler technological difficulties. I love nullable delegates.
I guess one reason is support for multi cast delegates Multi cast delegates are more complex than simply a few fields indicating target and method.
Another thing that's only possible in this form is delegate variance. This kind of variance requires a reference conversion between the two types.
Interestingly F# defines it's own function pointer type that's similar to delegates, but more lightweight. But I'm not sure if it's a value or reference type.

Why are Action<T> and Predicate<T> used or defined as delegates?

Can somebody explain what is the exact reason behind using Action<T> and Predicate<T> as delegates in C#
Are you asking why they exist, or why they're defined as delegates?
As to why they exist, perhaps the best reason is convenience. If you want a delegate that returns no value and takes a single parameter of some type, they you could define it yourself:
public delegate void MyDelegate(int size);
And then later create one:
MyDelegate proc = new MyDelegate((s) => { // do stuff here });
And, of course, you'd have to do that for every different type you want to have such a method.
Or, you can just use Action<T>:
Action<int> proc = new Action<int>((s) => { /* do stuff here */ });
Of course, you can shorten that to:
Action<int> proc = (s) => { /* do stuff here */ });
As to "why are they delegates?" Because that's how function references are manipulated in .NET: we use delegates. Note the similarities in the examples above. That is, MyDelegate is conceptually the same thing as an Action<int>. They're not exactly the same thing, since they have different types, but you could easily replace every instance of that MyDelegate in a program with Action<int>, and the program would work.
What else would they be? Delegates are the most flexible and closest match to what Action<T>, Predicate<T> and Func<T> are modlling - an invocation list with specified parameter types (aka delegates).
The best way to explain why the idiom for performing action and predicate operations using the Action<T> and Predicate<T> delegates was chosen is to first consider the alternative. How could you accomplish the same thing without delegates? The next best thing would be to have interfaces IAction and IPredicate and force developers to declare a class and implement the appropriate interface for each different type of operation needed. But, the problem with that approach is that it requires more effort, more class proliferation, and less maintainable code. The delegate approach is a lot more convenient because you can write the logic inline with where it will be used using anonymous methods or lambda expressions.
Because they are delegates.
You are looking at the problem from the wrong point of view.
The question should not be "Why are Action<>, Func<> & Predicate<> delegates?" (The answer to that is "because they need to be")
The real question is, "Why do we have specific named objects, to handle simple delegate tasks? Why use Action<> in a place where a ordinary delegate would work?"
The answer is that those particular delegates are used a lot on the CLR itself, and since that they are used in CLR methods where the end developers will have to defined the method being called, the declaration for the delegate would have to be public. So, Microsoft could have defined thousands of delegates, each used by just one CLR method, or define a simple way to specific what type of delegate is needed.

Heterogenic list of delegates

Is it possible to create a list containing delegates of different types ?
For example considere this two delegates :
class MyEventArg1 : EventArgs {}
class MyEventArg2 : EventArgs {}
EventHandler<MyEventArgs1> handler1;
EventHandler<MyEventArgs2> handler2;
I would like to do something like that :
List<EventHandler<EventArgs>> handlers = new List<EventHandler<EventArgs>>();
handlers.Add((EventHandler<EventArgs>)handler1);
handlers.Add((EventHandler<EventArgs>)handler2);
But the cast from one delegate to another seems not possible.
My goal is to store the delegates in a list not to call them; but just to unregister them automaticly.
Thanks
You will be able to do this in C# 4.0 thanks to the generics variance but until then you need to find another way (maybe ArrayList).
Yes, this doesn't work, the delegates are completely unrelated types. Normally, generic types would have only System.Object as the common base type. But here, since they are delegates, you could store them in a List<Delegate>. I doubt that's going to help you getting them unregistered though. But I can't really envision what that code might look like.
It's possible for a generic delegate declaration to specify that certain type parameters should be covariant or contravariant, which would allow the types of assignments you're after. Unfortunately, the internal implementation of multicast delegates makes it impossible to combine delegates of different types (a "simple" delegate holds information about its type, along with a method pointer and a reference to its target; a multicast delegate information about its type along with holds the method pointers and target references for each of its constituent delegates, but does not hold any reference to the original delegates that were combined, nor does it hold any information about their types). An attempt to combine an EventHandler<DerivedEventArgs> with an EventHandler<EventArgs> will thus fail at run-time.
If EventHandler<T> were contravariant with respect to T, an attempt to pass an EventHandler<EventArgs> to a standard event AddHandler method which expects an EventHandler<DerivedEventArgs> would compile, and would even succeed if no other handlers were subscribed, since the EventHandler<EventArgs> would be Delegate.Combined with null, thus being stored in the event's delegate field as an EventHandler<EventArgs>. Unfortunately, a subsequent attempt to add anEventHandler<DerivedEventArgs> (which is actually the expected type) would fail since its type doesn't match the delegate it's being combined with. Microsoft decided this behavior would violate the Principle of Least Astonishment (if passing the "wrong" delegate will cause any problem, it should do so when that delegate is passed, rather than when a later one is passed), and decided to minimize the likelihood of the scenario by making it so that an attempt to pass an EventHandler<EventArgs> to a handler that expects an EventHandler<DerivedEventArgs> will fail compilation, even though the act could succeed if it was the only subscription.

Categories