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

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);.

Related

How do I invoke a Delegate faster than by using DynamicInvoke?

Currently I useDynamicInvokewhich is very slow. Still using theDelegatetype how can I directly invoke the Delegate without late-binding/theDynamicInvoke?
Delegate _method;
_method.DynamicInvoke(_args);
Thanks.
The open source framework Impromptu-Inteface adds an extension method to Delegate called FastDynamicInvoke that runs a little over 20 times faster than DynamicInvoke by using the DLR instead of reflection.
using ImpromptuInterface
...
_method.FastDynamicInvoke(_args);
Invoke is faster, but it's a bit "hidden". From MSDN on Delegate class
The common language runtime provides
an Invoke method for each delegate
type, with the same signature as the
delegate. You do not have to call this
method explicitly from C#, Visual
Basic, or Visual C++, because the
compilers call it automatically. The
Invoke method is useful in reflection
when you want to find the signature of
the delegate type.
What this means is that when you create a delegate type, the Invoke member is added with the correct signature by the compiler. This allows calling without going through DynamicInvoke
In c#, you use this like:
_method(_args);
//or
_method(typedArg1, typedArg2, andSoOn);
calling it as you would a normal method. This actually calls Invoke, which should be much faster for you.

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.

What is delegate in C#? [duplicate]

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.

Best practices: When should I use a delegate in .NET? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Delegate Usage : Business Applications
Where do I use delegates?
Hi,
I'm new to the concept of a delegate in .NET - I haven't really used them yet and think they are probably there for a good reason - when should I be using a delegate?
Examples are very welcome.
Delegates provide a way for you to pass behavior as a parameter.
Common examples are Events and asynchronous programming where something other than your object is responsible for calling into your object. You provide that event with a delegate, and now it's able to run the behavior associated with that delegate.
This can also be a useful technique when implementing a general algorithm. There've been times where I'm writing multiple methods that are very similar. Perhaps they loop over the same set of data, but they perform slightly different tasks. I can pass in a delegate to a single function to perform that task, then call the delegate from inside the loop over the data. This way I don't have to implement the loop over the data multiple times, I only have to write new code that does new things-- the common behavior is all captured in a common way.
In response to the comment:
The difference between calling the delegate from within the loop and calling the method from within the loop is that the delegate is a parameter to the function that contains the loop. This means that that function could do anything, not just what's defined within a particular method. That flexibility can and has been leveraged to supply generic algorithms in libraries completely independent of the specifics of what the algorithms are working with. Linq is a fine example of the generality that is allowed via the flexibility of delegates.
Delegates are useful when you need to tell another piece of code how to do something. Events are the simplest example - separating the event (something happened) from how to handle it. Other examples are some common iterative operations, such as a custom find:
List<Foo> foos = new List<Foo>();
foos.Find(delegate(Foo foo)
{
if(foo.CustomProperty.Contains("special value"))
{
return false;
}
return true;
});
The above is a totally arbitrary example but makes the point that you can separate the what (iterating and running a "find" criteria) from the how (how to determine whether something is found).
Also, I would recommend using generic delegate types instead of creating your own. Examples below:
EventHandler< TEventArgs>
Func< TResult>
Func< T1, T2, TResult>
Func etc...
Action< T1>
Action< T1, T2>
Action etc...
Events use delegates behind the scenes.
If you use events you've used delegates but just with a nicer syntax.
Basically one use for them is for callbacks or event based programming.
Delegates are used for event driven programming. Best practices are often about decoupling code (or 'loose' coupling). Using delegates you can subscribe methods to events, instead of having X call Y if something happens, and then Y call Z under a certain condition and so forth.
Events and Callbacks in the .NET guidelines explains it well.
In summary, you should prefer events in simple APIs because there is strong IDE support and most developers are comfortable with events. However, if you need the user to provide code that will be executed, you should consider using delegates or virtual members. Callbacks are less performant, but if you use delegates like Action and Func you allow lambdas.
Example case: a single resource is being used by multiple objects. The resource needs an asynchronous callback to these objects, but the nature of the resource demands that only one request be active at a given time, and that request is tied to a particular object. Due to the architecture, I don't want to pass the objects into the resource, so instead, I send the resource a delegate from each object and store these delegates along with object identifiers. When a request is made, I can look up the corresponding object identifier and call its specific delegate.
I originally implemented this with an event, but since the event couldn't be 'aimed' at a particular object, I was having issues. I'm not sure this is best practice, but it seems to work well for me.

Categories