Core Use of Delegates [duplicate] - c#

This question already has answers here:
The purpose of delegates [duplicate]
(7 answers)
Where do I use delegates? [closed]
(8 answers)
What are the advantages of delegates? [duplicate]
(7 answers)
Closed 9 years ago.
I am a newbie in c#. I were able to understand the concepts of Delegates like syntax, how to use Delegates. But I still confused about "Why we use delegates". Because It finally used to call a method. Why we go for delegates?

We use delegates to be able to call a method at a later time in the execution of the code. We can pass a method to another block of code which can decide if and when to call it.
In this way we can delegate the responsibility for calling a method.

You may consider delegates as a way to "inject" your code with predefined contract in some execution chain.

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.
It is mainly used in event handlers, but that is not it's only usage; See the details of delegates at - http://msdn.microsoft.com/en-us/library/aa288459%28v=vs.71%29.aspx

You can have a look at this answer as to the use of delegates.
What are the advantages of delegates?
There are multiple Question in this area that you can browse through.

Delegates can be sent to another function, in essence making part of the function "customizable".
//both of these calls use the same function (Where) but with a different predicate delegate
var greaterThanZero = intList.Where(e => e > 0);
var lessThanZero = intList.Where(e => e < 0);

Delegates are used for many things. The most common use if for event handlers. The code that generates the event need know nothing about the code that will handle the event, which can be supplied by a 3rd party. In other words, Microsoft can supply event firing code, leaving you to supply the methods that will handle those events.
Delegates can be used in any situation like this where you provide some sort of generic handler and other code does something specific with it.
Another way to view delegates is that they are the way C# handles the Command Pattern. Rather than having to declare the interfaces and classes often associated with that patetrn in order to call a method, C# lets you pass references to methods around directly, greatly simplifying the way that pattern is implemented in C#.

you can imagine a simple example: in your application for export result you have below options
1. export to pdf
2. export tp csv
3. export to txt
All 3 option will have different method implementation, and these method will do SOMETHING with your data.
suppose above three will call below 3 methods respectively:
1. ExportToPdf(Data, filepath.pdf)
2. ExportToCsv(Data, filepath.csv)
3. ExportToTxt(Data, filepath.txt)
As you can see all 3 have same method signature. In future you may have further types of exports also which you don't know as of now. You will use delegate here which will have same method signature, in place of any specific method.
Apart from this, there are other uses of Delegate like, EventHandler, Async method invocation using BeginInvoke.

Related

C#: Anonymous method vs Named method

I'm new to SO and programming and learning day by day with bits and pieces of tech (C#) jargons.
After Googling for a while, below is what I've researched about methods
A Method is a block of statements, which serves for code reusability
& it also supports overloading with different SIGNATURE....for ex:
drawShape(2pts), drawShape(3pts) etc...
An Anonymous method is one with block of statements, but no
name....(as its premature to ask, in wt situation we come across
anonymous method...any articles, samples ...)
Named method: Here's a link but at the end i didn't get what Named Method actually is...
Can anyone explain what a "Named" method is, and where do we use anonymous method?
A named method is a method you can call by its name (e.g. it is a function that has a name). For example, you have defined a function to add two numbers:
int f(int x, int y)
{
return x+y;
}
You would call this method by its name like so: f(1, 2);.
Anonymous method is a method that is passed as an argument to a function without the need for its name. These methods can be constructed at runtime or evaluated from a lambda expression at compile time.
These methods are often used in LINQ queries, for example:
int maxSmallerThan10 = array.Where(x => x < 10).Max();
The expression x => x < 10 is called a lambda expression and its result is an anonymous function that will be run by the method Where.
If you are a beginner, I would suggest you first read about more basic stuff. Check out the following links:
http://www.completecsharptutorial.com/
http://www.csharp-station.com/tutorial.aspx
http://www.homeandlearn.co.uk/csharp/csharp.html
Let's start from a simple method.
void MyMethod()
{
Console.WriteLine("Inside MyMethod"); //Write to output
}
The above method is a named-method which just writes Inside MyMethod to the output window.
Anonymous methods are some methods used in some special scenarios (when using delegates) where the method definition is usually smaller where you don't specify the name of the method.
For example, (delegate) => { Console.WriteLine("Inside Mymethod");}
Just start writing some simple programs and in the due course, when you use delegates or some advanced concepts, you will yourself learn. :)
Explanation by Analogy
Normally when we tell stories we refer to people by name:
"Freddie"
"Who's Freddie?"
"You know, Freddie, Freddie from Sales - the male guy with the red hair, who burned the building down...?"
In reality nobody cares who the person is, department he works etc. it's not like we'll refer to him every again. We want to be able to say: "Some guy burned down our building". All the other stuff (hair color, name etc.) is irrelevant and/or can be inferred.
What does this have to do with c#?
Typically in c# you would have to define a method if you want to use it: you must tell the compiler (typically):
what it is called,
and what goes into it (parameters + their types),
as well as what should come out (return type),
and whether it is something you can do in the privacy of your home or whether you can do it in public. (scope)
When you do that with methods, you are basically using named methods. But writing them out: that's a lot of effort. Especially if all of that can be inferred and you're never going to use it again.
That's basically where anonymous methods come in. It's like a disposable method - something quick and dirty - it reduces the amount you have to type in. That's basically the purpose of them.
Anonymous methods or anonymous functions, what seems to be the same, basically are delegates. As the link you point out: http://msdn.microsoft.com/en-us/library/bb882516.aspx describes, anonymous methods provide a simplified way to pass method to be executed by another method. Like a callback.
Another way to see it, is think about lambda expressions.
A named by the contrast is any common method.
From MSDN:
A delegate can be associated with a named method. When you instantiate a delegate by using a named method, the method is passed as a parameter. This is called using a named method. Delegates constructed with a named method can encapsulate either a static method or an instance method. Named methods are the only way to instantiate a delegate in earlier versions of C#. However, in a situation where creating a new method is unwanted overhead, C# enables you to instantiate a delegate and immediately specify a code block that the delegate will process when it is called. The block can contain either a lambda expression or an anonymous method.
and
In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide). Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
So in answer to your question about when to use anonymous methods, then MSDN says: in a situation where creating a new method is unwanted overhead.
In my experience it's more down to a question of code reuse and readability.
Links:
http://msdn.microsoft.com/en-us/library/98dc08ac.aspx
http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
Hope that helps

Is there a way of calling a Functional "Invoke" without using Reflection?

Is there any way, without using Reflection, of writing something along the lines of OSteele's Functional Invoke in C#?
This means using it as in:
Action<T> MethodName = StaticUtil.Invoke<T>("MethodName", optionalCurriedArgs);
And then calling:
MethodName(objWithMethodName);
I know using a Lambda would do the trick.
What I mean, is using something along the lines of AS3's:
public static function invoke( selectedMethod : String, ... arguments ) : Function {
var args : Array = arguments.slice();
return function ( object : * ) : * {
return object[ selectedMethod ].apply( object, args);
};
}
Thank you for reading.
No. There is no obvious way in C# without using Reflection to call a function on a particular class. At best you might try dynamic and let it be resolved at runtime. You can try using a library like FasterFlect to solve your need.
Alternatively, if you want a built in method you can do
typeof(MyObject).InvokeMember(methodName
,BindingFlags.Public | BindingFlags.Instance
,null
,myInstance
,new object[]{parameter1,parameter2})
I would be lying to you if I said it wasn't reflection though. The CLR wasn't designed for you to invoke methods dynamically like javascript. This was a conscious decision to make a high performance method call. If you need to pass functions around use Delegates. If your method needs variable argument support you can use overloads, or params. If you need to call methods dynamically via strings:
use Dictionary<string,DelegateType> or if you know you have a few methods and need absolute speed use a List<Tuple<string,DelegateType>>. If you have many types that all respond to a message use Interfaces. If the classes aren't your own, or they are specialized for primitives try dynamic.
C# is a well designed language written for standard coding practices. There are lots of options. If you really need to they give you the tools to look up members and invoke them. Reflection is slow because the CLR was designed to be SAFE first. If you find yourself needing lots of reflection dynamic invocation you might want to reconsider your design choices. If you still can find no other way you can still use caching and Delegates to make that fast. dynamic is entirely done with clever caching and delegates, and dynamic in the best cases is nearly as fast as native code.
In theory, you can create a pattern like CallSite<T> in the DLR to fast cache a particular call site. I do something similar in a dynamic proxy I wrote to get around the fact that there is no way to create a function pointer to an open generic method. (e.g. I wanted to have a mydelegate.Invoke<T>(T arg) ).

Why do we need C# delegates

I never seem to understand why we need delegates?
I know they are immutable reference types that hold reference of a method but why can't we just call the method directly, instead of calling it via a delegate?
Thanks
Simple answer: the code needing to perform the action doesn't know the method to call when it's written. You can only call the method directly if you know at compile-time which method to call, right? So if you want to abstract out the idea of "perform action X at the appropriate time" you need some representation of the action, so that the method calling the action doesn't need to know the exact implementation ahead of time.
For example:
Enumerable.Select in LINQ can't know the projection you want to use unless you tell it
The author of Button didn't know what you want the action to be when the user clicks on it
If a new Thread only ever did one thing, it would be pretty boring...
It may help you to think of delegates as being like single-method interfaces, but with a lot of language syntax to make them easy to use, and funky support for asynchronous execution and multicasting.
Of course you can call method directly on the object but consider following scenarios:
You want to call series of method by using single delegate without writing lot of method calls.
You want to implement event based system elegantly.
You want to call two methods same in signature but reside in different classes.
You want to pass method as a parameter.
You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the Select method.
Because you may not have the method written yet, or you have designed your class in such a way that a user of it can decide what method (that user wrote) the user wants your class to execute.
They also make certain designs cleaner (for example, instead of a switch statement where you call different methods, you call the delegate passed in) and easier to understand and allow for extending your code without changing it (think OCP).
Delegates are also the basis of the eventing system - writing and registering event handlers without delegates would be much harder than it is with them.
See the different Action and Func delegates in Linq - it would hardly be as useful without them.
Having said that, no one forces you to use delegates.
Delegates supports Events
Delegates give your program a way to execute methods without having to know precisely what those methods are at compile time
Anything that can be done with delegates can be done without them, but delegates provide a much cleaner way of doing them. If one didn't have delegates, one would have to define an interface or abstract base class for every possible function signature containing a function Invoke(appropriate parameters), and define a class for each function which was to be callable by pseudo-delegates. That class would inherit the appropriate interface for the function's signature, would contain a reference to the class containing the function it was supposed to represent, and a method implementing Invoke(appropriate parameters) which would call the appropriate function in the class to which it holds a reference. If class Foo has two methods Foo1 and Foo2, both taking a single parameter, both of which can be called by pseudo-delegates, there would be two extra classes created, one for each method.
Without compiler support for this technique, the source code would have to be pretty heinous. If the compiler could auto-generate the proper nested classes, though, things could be pretty clean. Dispatch speed for pseudo-delegates would probably generally be slower than with conventional delegates, but if pseudo-delegates were an interface rather than an abstract base class, a class which only needs to make a pseudo-delegate for one method of a given signature could implement the appropriate pseudo-delegate interface itself; the class instance could then be passed to any code expecting a pseudo-delegate of that signature, avoiding any need to create an extra object. Further, while the number of classes one would need when using pseudo-delegates would be greater than when using "real" delegates, each pseudo-delegate would only need to hold a single object instance.
Think of C/C++ function pointers, and how you treat javascript event-handling functions as "data" and pass them around. In Delphi language also there is procedural type.
Behind the scenes, C# delegate and lambda expressions, and all those things are essentially the same idea: code as data. And this constitutes the very basis for functional programming.
You asked for an example of why you would pass a function as a parameter, I have a perfect one and thought it might help you understand, it is pretty academic but shows a use. Say you have a ListResults() method and getFromCache() method. Rather then have lots of checks if the cache is null etc. you can just pass any method to getCache and then only invoke it if the cache is empty inside the getFromCache method:
_cacher.GetFromCache(delegate { return ListResults(); }, "ListResults");
public IEnumerable<T> GetFromCache(MethodForCache item, string key, int minutesToCache = 5)
{
var cache = _cacheProvider.GetCachedItem(key);
//you could even have a UseCache bool here for central control
if (cache == null)
{
//you could put timings, logging etc. here instead of all over your code
cache = item.Invoke();
_cacheProvider.AddCachedItem(cache, key, minutesToCache);
}
return cache;
}
You can think of them as a construct similar with pointers to functions in C/C++. But they are more than that in C#. Details.

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