How and why should I use Events and delegates - c#

I read about events and delegates. I think I understand how they work but I do not understand why should I use them.
For example, I have online shop where customer has balance and is buying products using this money.
This is enough to do the job.
When user buys something, sells something or deposits money - UserWallet class is called.
class Shop
{
public static void BuyOrderFilled(){
if(userHasBalance()){
UserWallet userWallet = new UserWallet();
userWallet.DeductMoney();
}
UpdateInventory();
}
public static void SellOrderFilled(){
//Sell order has different logic
if(userHasProduct()){
UserWallet userWallet = new UserWallet();
userWallet.RemoveProductFromUser();
}
UpdateInventory();
}
}
class Deposit{
public static void UserGotDeposit(decimal amount){
UserWallet userWallet = new UserWallet();
userWallet.FillUserBalance(amount);
}
}
class UserWallet{
public void DeductMoney(){
//Some logic
}
public void RemoveProductFromUser(){
//Some logic
}
public void FillUserBalance(){
//Some logic
}
}
public class Main(){
Shop.BuyOrderFilled();
Shop.SellOrderFilled();
Deposit.UserGotDeposit(100);
}
Why should I use Events or delegates when I can just call UserWallet methods whenever I need them?

You don't have to use them..
..it's just that sometimes it's super handy to be able to pass methods around like they were data.
Quite often the utility in this is if you're providing a library for other people to use and you want to make it useful for them but you don't know a thing about their code or how they'll use it. An obvious one is List<T> in the framework; you might be writing something like it and want to provide a way for people to search if, but you don't know what kind of objects they will put in the list or how they want to search for them.
If, however you just provide them with a method like Find(delegate) then it's a "method that takes a method as a parameter" - you declare to the user "provide Find with a method that takes a T and returns a boolean of true if it should be included in the search results", then it means they can write a method like this:
bool IsSmith(Person p) {
return p.LastName == "Smith";
}
And they can pass it to your list Find method, your method runs their method, gives it the List object, gets a bool and decides what to do based on the result
var smiths = myListOfPeople.Find(IsSmith);
Nowadays we don't usually write the method out so long hand, we use the funky inline declaration where we just provide the parameter name and the logic, and the compiler inserts all the other stuff it can work out
var smiths = myListOfPeople.Find(p => p.LastName == "Smith");
In essence you can control every part of the process when you wrote your List class, you can implement the find, you can return the results - but in making your List truly flexible and letting people store what they want in it, you create a gap in the middle where you can't know how to search for a Whatever that the user put into it. Being able to let them pass a method in (of a known arguments type and return type) that you can call closes that gap
Another example; events this time but they're no different. An event is just a list of methods that the user of your class can fill with "bits of code that shall be run when something happens"
Take a button click: you want to download a file, your coworker wants to save an image, I want to calculate factors of a number entered in a text box.. We're all using that same Button class but we all want to do different things when we click our different buttons, so the easiest way for Microsoft to make the perfect button is to just leave that "do this when clicked" part for us to fill in, and that's done by having a way to associate a delegate (method passed round like a variable) with the button, and coding the button so that it runs the delegate when it's clicked, whatever the delegate may do
So all that is great for Microsoft, who create Buttons and Lists and other generic things for us to enjoy, but does it have a place for us in our own code? Sure, though more rare, I find it helpful to make some helper class for example- something that launches ffmpeg and reads from its output stream.. and mostly it's just nonsense but occasionally interesting messages are sent, so I might make an event that I raise when such a message is sent.. I use my helper in one project and I'm looking for dropped frames, in another I want to know if silence is detected.. In those cases I suppose the "person who provides the library to the person who consumes the library" was me at both ends. I have other projects where I want to perform similar tasks on different data, the writer routine is the same but the parsing is different; being able to pass a method to say how to pull a name out of this object but a number out of that one makes life a lot nicer than having some massive "if object is a person pull the name, else if object is a building pull the number and street" conditional block in a place it doesn't belong

Related

Method in method in method c#

Is it bad to have a lot of methods referring to each other, like the following example?
public void MainMethod()
{
GetProducts();
}
public void GetProducts()
{
var _products = new Products();
var productlist = _products.GetProductList;
GetExcelFile(productlist);
}
public void GetExcelFile(List<product> productlist)
{
var _getExcelFile = new GetExcelFile();
var excelfile = _getExcelFile.GetExcelFileFromProductList(productlist);
//create excel file and so on...
}
So I am creating a new method for every little action. It would be just as easy to call GetProducts from the MainMethod and do all actions in that method, but I think that isn't the way to create re-usable code.
The following tells me that there should be no more than 7 statements in a method:
Only 7 statements in a method
So the advantages of using methods with a minimal amount of code:
Code is re-usable
Every task can get his own method
The disadvantages of using methods with a minimal amount of code:
It's like spaghetti code
You get: refer to refer and so on
My question:
Should my methods be bigger, or should I keep creating small methods, that do little and refer to a lot of other methods?
The guideline is right. Methods should be small and you are doing the right thing be giving not only each operation its own method, but a well defined name. If those methods have a clear name, one responsibility and a clear intention (and don't forget to separate commands from queries), your code will not be spagetti. On top of that, try to order methods like a news article: most important methods on top of the file, methods with the most detail on the bottom. This way anyone else can start reading at the top and stop reading when they're bored (or have enough information).
I can advice you to get a copy of Robert Martin's Clean Code. There's no one in the industry who describes this more clearly than he does.
The guideline is generally a good one, not so much for reuse, but for readability of your code.
Your example, though, is not a good one. What you're doing is basically creating a long list of methods where each one stops when you feel it's too long and calls another one to perform the rest of the operations.
I would follow more this kind of approach, where reading the main method tells you the "story" that your code needs to tell by steps and the detail of each step is in smaller methods.
public void MainMethod()
{
var productlist=GetProducts();
string excelfile=GetExcelFile(productlist);
// do something in the excel file
}
public List<product> GetProducts()
{
var _products = new Products();
return _products.GetProductList;
}
public string GetExcelFile(List<product> productlist)
{
var _getExcelFile = new GetExcelFile();
var excelfile = _getExcelFile.GetExcelFileFromProductList(productlist);
return excelfile;
}
I don't really agree with '7 statements in a method'. A method can have dozens of statements, as long as the method performs a single function and the specific logic will only be used in one place, I don't really see the point of cutting it into parts just because some guyideline says so, it should be seperated based on what makes sense.
Re-use of code is good if it makes sense, but I don't think you should make everything everywhere re-usable, when you have no plans in the near future to actually re-use it. It increases the development time needlessly, it often makes the software more complex and harder to interpret then it needs to be, and (at least in my company) the majority of the code never gets re-used, and even if it is it still needs modifications in new products. Only the most generic parts of our codebase actually gets used in several applications without modifications for each product.
And I think that's fine.
this is mostly opinion based question, but i'll tell you one thing:
if you're not going to use a method from more then one place, it might be better not to create a method for that.
you can use regions for clarity and you might not want a method that is larger then a full page, but not every 2-3 commands should get a method.

Delegates vs. Events

When a class can't (or should not) do something, then events or delegates could be a solution.
say
class President
Event AskedQuestion(QuestionEventArgs)
Delegate GetAnswerToQuestion
class Scientist
AnswerToQuestion()
// delegate approach
myPresident.GetAnswerToQuestion = AddressOf myScientist.AnswerToQuestion
// called once myPresident need it
// event approach
myScientist.AnswerToQuestion(questionEventArgs) Handles President.AskedQuestion
{
// executed once president asked a question
}
Here in the delegate approach Scientist method is used directly by the President class, in the event one President raises a question, and the Scientist react to it with an answer.
In the .NET Framework code I didn't observe, however the direct use of delegates. Is it wrong to use it directly, and if, why?
Is it wrong to use it directly, and if, why?
No, it's not wrong.
Here's how I think about it. Delegate fields are to events as string fields are to properties. That is, you might have:
class Car
{
private string modelName;
public string ModelName { get { return this.modelName; } }
...
The model name is logically a property of a car. When someone asks you what kind of car you drive and you say "a Ford Focus", you are describing a property of the car. You do not think of "Ford Focus" as being a "field" or a "string", you think of it as being the name of a kind of car. In the computer program, the string field is just the implementation detail of how the name is stored. The property could be a string, or it could be an enum, or whatever; the point is that logically, cars have model names, not string fields.
Events and delegates are the same way. A car can have an "explode" event (perhaps you are writing a video game!) and the explode event is implemented by a field of delegate type. Exploding is something the car logically does; the delegate field is the mechanism by which the event is implemented.
So is it "wrong" to use delegates directly? No, of course not. No more than it is "wrong" to use strings directly. Sometimes you need to manipulate strings that are not properties, and sometimes you need to manipulate delegates that are not events.
The trick is to write code that clearly separates the mechanical processes from the business processes. If you find that you're mixing a lot of string logic with your property logic, or mixing a lot of delegate manipulation with your events, then you might consider trying to separate the mechanism code from the business code a bit more, so that it is easier to see which is which.
There is plenty of use of delegates in the framework. LINQ is a clear example of this:
var result = someCollection.Where(input => input.MatchesSomeCriteria);
Where takes a delegate with a specific signature which is invoked in order to determine whether to include an item in the result or not. The most common use is the lamba approach as shown above, but you can just as well pass a method:
string[] nums = new[]{ "1", "2", "3"};
int sum = nums.Select(int.Parse).Sum();
int.Parse matches the required delegate signature that Select expects in this case (Func<string,int>), so it will be invoked for each of the strings in nums.
Typically when delegates are used directly, they are taken as input to method calls that will consume them. There are some places where they are part of the consumers state though (HttpListener for instance has a few properties that are of delegate types), but they are not that many.
working with delegates in the raw can entail some
boilerplate code (defining the delegate, declaring necessary member variables, and creating custom
registration/unregistration methods to preserve encapsulation, etc.).
Typing time aside, another issue with using delegates in the raw as your application’s callback
mechanism is the fact that if you do not define a class’s delegate member variables as private, the
caller will have direct access to the delegate objects. If this were the case, the caller would be able to
reassign the variable to a new delegate object (effectively deleting the current list of functions to
call) and worse yet, the caller would be able to directly invoke the delegate’s invocation list.
events
events are actually one of the things that I really like about .net becuase it lets you declare a much cleaner interface. You can have a president class that announces that it needs an answer without binding it to the implementation of the answering agent like
interface IPresident
{
event Action<QuestionArgs, IPresident> HasQuestion;
void RecieveAnswer(QuestionArgs,Answer);
}
and then in your scientist class
partial class Scientist
{
public Scientist(IPresident president)
{
president.HasQuestion += TryToAnswerQuestion;
}
private void TryToAnswerQuestion(QuestionArgs question, IPresident asker)
{
if(CanAnswerQuestion(question))
{
asker.RecieveAnswer(question,GetAnswer(question));
}
}
}
If a new class wants to answer the presidents questions all they need to do is listen for the event signaling that there is a question that needs to be answered and then answer it if they are able to. If the scientist wants to answer questions from someone else we just need to implement a method that attaches to their Event.
direct delegate invocation
The problem with the delegate approach that you outlined above is that it breaks encapsulation. It tightly couples the scientist and president implementations and makes the code brittle. What happens when you have some other person that answers questions? In your example you are going to need to modify your Scientist implementation in order to add new functionality this is referred to as "brittle" code and is a bad thing. This technique does have some role in composition but it will only rarely, if ever, be the best choice.
the linq case is different, because you aren't exposing a delegate as a member of a class/interface. Instead you are using it as a functor declared by the caller to let you know what information the caller is interested in. Since you are making a "round-trip" encapsulation stays intact.
This lets you define very clean and powerful APIs.
We could take the Scientist example and extend it using this technique to allow someone to find out what questions we can answer like this
partial class Scientist
{
public IEnumerable<QuestionArgs> FindQuestions(Predicate<QuestionArgs> interest, IPresident asker)
{
return this.Questions.Where( x => interest(x) == true && x.IsAuthorizedToAsk(asker))
}
}
// ...
partial class President
{
FirePhysicists()
{
foreach(var scientist in scientists)
{
if(scientist.FindQuestions(x => x.Catagory == QuestionCatagory.Physics, this).Count != 0)
{
scientist.Fire();
}
}
}
}
Note how the FindQuestions method let us not have to implement a bunch of other code to interrogate the scientist that we would have needed without the ability pass delegates around. While this isn't the only case where you are going to find delegates invoked directly it is one of the most common ones

why do we need delegates [duplicate]

I'm looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I've heard that delegates can be used for this, but can't figure out why they would be preferred over plain old interfaces implemented on observers. So,
Why should I use delegates instead of defining my own interfaces and passing around references to objects implementing them?
Why might I want to avoid using delegates, and go with good ol'-fashioned interfaces?
When you can directly call a method, you don't need a delegate.
A delegate is useful when the code calling the method doesn't know/care what the method it's calling is -- for example, you might invoke a long-running task and pass it a delegate to a callback method that the task can use to send notifications about its status.
Here is a (very silly) code sample:
enum TaskStatus
{
Started,
StillProcessing,
Finished
}
delegate void CallbackDelegate(Task t, TaskStatus status);
class Task
{
public void Start(CallbackDelegate callback)
{
callback(this, TaskStatus.Started);
// calculate PI to 1 billion digits
for (...)
{
callback(this, TaskStatus.StillProcessing);
}
callback(this, TaskStatus.Finished);
}
}
class Program
{
static void Main(string[] args)
{
Task t = new Task();
t.Start(new CallbackDelegate(MyCallbackMethod));
}
static void MyCallbackMethod(Task t, TaskStatus status)
{
Console.WriteLine("The task status is {0}", status);
}
}
As you can see, the Task class doesn't know or care that -- in this case -- the delegate is to a method that prints the status of the task to the console. The method could equally well send the status over a network connection to another computer. Etc.
You're an O/S, and I'm an application. I want to tell you to call one of my methods when you detect something happening. To do that, I pass you a delegate to the method of mine which I want you to call. I don't call that method of mine myself, because I want you to call it when you detect the something. You don't call my method directly because you don't know (at your compile-time) that the method exists (I wasn't even written when you were built); instead, you call whichever method is specified by the delegate which you receive at run-time.
Well technically, you don't have to use delegates (except when using event handlers, then it's required). You can get by without them. Really, they are just another tool in the tool box.
The first thing that comes to mind about using them is Inversion Of Control. Any time you want to control how a function behaves from outside of it, the easiest way to do it is to place a delegate as a parameter, and have it execute the delegate.
You're not thinking like a programmer.
The question is, Why would you call a function directly when you could call a delegate?
A famous aphorism of David Wheeler
goes: All problems in computer science
can be solved by another level of
indirection.
I'm being a bit tongue-in-cheek. Obviously, you will call functions directly most of the time, especially within a module. But delegates are useful when a function needs to be invoked in a context where the containing object is not available (or relevant), such as event callbacks.
There are two places that you could use delegates in the Observer pattern. Since I am not sure which one you are referring to, I will try to answer both.
The first is to use delegates in the subject instead of a list of IObservers. This approach seems a lot cleaner at handling multicasting since you basically have
private delegate void UpdateHandler(string message);
private UpdateHandler Update;
public void Register(IObserver observer)
{
Update+=observer.Update;
}
public void Unregister(IObserver observer)
{
Update-=observer.Update;
}
public void Notify(string message)
{
Update(message);
}
instead of
public Subject()
{
observers = new List<IObserver>();
}
public void Register(IObserver observer)
{
observers.Add(observer);
}
public void Unregister(IObserver observer)
{
observers.Remove(observer);
}
public void Notify(string message)
{
// call update method for every observer
foreach (IObserver observer in observers)
{
observer.Update(message);
}
}
Unless you need to do something special and require a reference to the entire IObserver object, I would think the delegates would be cleaner.
The second case is to use pass delegates instead of IObervers for example
public delegate void UpdateHandler(string message);
private UpdateHandler Update;
public void Register(UpdateHandler observerRoutine)
{
Update+=observerRoutine;
}
public void Unregister(UpdateHandler observerRoutine)
{
Update-=observerRoutine;
}
public void Notify(string message)
{
Update(message);
}
With this, Observers don't need to implement an interface. You could even pass in a lambda expression. This changes in the level of control is pretty much the difference. Whether this is good or bad is up to you.
A delegate is, in effect, passing around a reference to a method, not an object... An Interface is a reference to a subset of the methods implemented by an object...
If, in some component of your application, you need access to more than one method of an object, then define an interface representing that subset of the objects' methods, and assign and implement that interface on all classes you might need to pass to this component... Then pass the instances of these classes by that interface instead of by their concrete class..
If, otoh, in some method, or component, all you need is one of several methods, which can be in any number of different classes, but all have the same signature, then you need to use a delegate.
I'm repeating an answer I gave to this question.
I've always like the Radio Station metaphor.
When a radio station wants to broadcast something, it just sends it out. It doesn't need to know if there is actually anybody out there listening. Your radio is able to register itself with the radio station (by tuning in with the dial), and all radio station broadcasts (events in our little metaphor) are received by the radio who translates them into sound.
Without this registration (or event) mechanism. The radio station would have to contact each and every radio in turn and ask if it wanted the broadcast, if your radio said yes, then send the signal to it directly.
Your code may follow a very similar paradigm, where one class performs an action, but that class may not know, or may not want to know who will care about, or act on that action taking place. So it provides a way for any object to register or unregister itself for notification that the action has taken place.
Delegates are strong typing for function/method interfaces.
If your language takes the position that there should be strong typing, and that it has first-class functions (both of which C# does), then it would be inconsistent to not have delegates.
Consider any method that takes a delegate. If you didn't have a delegate, how would you pass something to it? And how would the the callee have any guarantees about its type?
I've heard some "events evangelists" talk about this and they say that as more decoupled events are, the better it is.
Preferably, the event source should never know about the event listeners and the event listener should never care about who originated the event. This is not how things are today because in the event listener you normally receive the source object of the event.
With this said, delegates are the perfect tool for this job. They allow decoupling between event source and event observer because the event source doesn't need to keep a list of all observer objects. It only keeps a list of "function pointers" (delegates) of the observers.
Because of this, I think this is a great advantage over Interfaces.
Look at it the other way. What advantage would using a custom interface have over using the standard way that is supported by the language in both syntax and library?
Granted, there are cases where it a custom-tailored solution might have advantages, and in such cases you should use it. In all other cases, use the most canonical solution available. It's less work, more intuitive (because it's what users expect), has more support from tools (including the IDE) and chances are, the compiler treats them differently, resulting in more efficient code.
Don't reinvent the wheel (unless the current version is broken).
Actually there was an interesting back-and-forth between Sun and Microsoft about delegates. While Sun made a fairly strong stance against delegates, I feel that Microsoft made an even stronger point for using delegates. Here are the posts:
http://java.sun.com/docs/white/delegates.html
http://msdn.microsoft.com/en-us/vjsharp/bb188664.aspx
I think you'll find these interesting reading...
i think it is more related to syntatic sugar and a way to organize your code, a good use would be to handle several methods related to a common context which ones belong to a object or a static class.
it is not that you are forced to use them, you can programme sth with and without them, but maybe using them or not might affect how organized, readable and why not cool the code would be, maybe bum some lines in your code.
Every example given here is a good one where you could implement them, as someone said it, is just another feature in the language you can play with.
greetings
Here is something that i can write down as a reason of using delegate.
The following code is written in C# And please follow the comments.
public delegate string TestDelegate();
protected void Page_Load(object sender, EventArgs e)
{
TestDelegate TD1 = new TestDelegate(DiaplayMethodD1);
TestDelegate TD2 = new TestDelegate(DiaplayMethodD2);
TD2 = TD1 + TD2; // Make TD2 as multi-cast delegate
lblDisplay.Text = TD1(); // invoke delegate
lblAnotherDisplay.Text = TD2();
// Note: Using a delegate allows the programmer to encapsulate a reference
// to a method inside a delegate object. Its like the function pointer
// in C or C++.
}
//the Signature has to be same.
public string DiaplayMethodD1()
{
//lblDisplay.Text = "Multi-Cast Delegate on EXECUTION"; // Enable on multi-cast
return "This is returned from the first method of delegate explanation";
}
// The Method can be static also
public static string DiaplayMethodD2()
{
return " Extra words from second method";
}
Best Regards,
Pritom Nandy,
Bangladesh
Here is an example that might help.
There is an application that uses a large set of data. A feature is needed that allows the data to be filtered. 6 different filters can be specified.
The immediate thought is to create 6 different methods that each return the data filtered. For example
public Data FilterByAge(int age)
public Data FilterBySize(int size)
.... and so on.
This is fine but is a very limited and produces rubbish code because it's closed for expansion.
A better way is to have a single Filter method and to pass information on how the data should be filtered. This is where a delegate can be used. The delegate is a function that can be applied to the data in order to filter it.
public Data Filter(Action filter)
then the code to use this becomes
Filter(data => data.age > 30);
Filter(data => data.size = 19);
The code data => blah blah becomes a delegate. The code becomes much more flexible and remains open.

Static Methods vs Class Instances and return values in C#

I have various classes for handling form data and querying a database. I need some advice on reducing the amount of code I write from site to site.
The following code is for handling a form posted via ajax to the server. It simply instantiates a Form class, validates the data and processes any errors:
public static string submit(Dictionary<string, string> d){
Form f = new Form("myform");
if (!f.validate(d)){
return f.errors.toJSON();
}
//process form...
}
Is there a way to reduce this down to 1 line as follows:
if (!Form.validate("myform", d)){ return Form.errors.toJSON(); }
Let's break that down into two questions.
1) Can I write the existing logic all in one statement?
The local variable has to be declared in its own statement, but the initializer doesn't have to be there. It's prefectly legal to say:
Form f;
if (!(f=new Form("myform")).validate(d))return f.errors.toJSON();
Why you would want to is beyond me; doing so is ugly, hard to debug, hard to understand, and hard to maintain. But it's perfectly legal.
2) Can I make this instance method into a static method?
Probably not directly. Suppose you had two callers validating stuff on two different threads, both calling the static Form.Validate method, and both producing errors. Now you have a race. One of them is going to win and fill in Form.Errors. And now you have two threads reporting the same set of errors, but the errors are wrong for one of them.
The better way to make this into a static method is to make the whole thing into a static method that has the desired semantics, as in plinth's answer.
Errors errors = Validator.Validate(d);
if (errors != null) return errors.toJSON();
Now the code is very clear, and the implementation of Validate is straightforward. Create a form, call the validator, either return null or the errors.
I would suggest that you don't need advice on reducing the amount of code you write. Rather, get advice on how to make the code read more like the meaning it intends to represent. Sometimes that means writing slightly more code, but that code is clear and easy to understand.
I would move all common validation logic to a superclass.
I think the main problem of your code is not that is long, but that you're repeating that in many places, either if you manage to make it a one-liner, it would not be DRY.
Take a look at the Template Method pattern, it might help here (The abstract class with the validation would be the Template and your specific 'actions' would be the subclasses).
Of course you could write this:
public static string FormValidate(Dictionary<string, string> d)
{
Form f = new Form("myform");
if (!f.validate(d))
return f.errors.ToJSON();
return null;
}
then your submit can be:
public static string submit(Dictionary<string, string> d)
{
if ((string errs = FormValidate(d))!= null) { return errs; }
// process form
}
That cuts down your code and doesn't hurt readability much at all.
If you really, really wanted to, you could store the error text in a thread-local property.
Does C# have a "ThreadLocal" analog (for data members) to the "ThreadStatic" attribute?

Uses of delegates in C# (or other languages)

I have always wondered how delegates can be useful and why shall we use them? Other then being type safe and all those advantages in Visual Studio Documentation, what are real world uses of delegates.
I already found one and it's very targeted.
using System;
namespace HelloNamespace {
class Greetings{
public static void DisplayEnglish() {
Console.WriteLine("Hello, world!");
}
public static void DisplayItalian() {
Console.WriteLine("Ciao, mondo!");
}
public static void DisplaySpanish() {
Console.WriteLine("Hola, imundo!");
}
}
delegate void delGreeting();
class HelloWorld {
static void Main(string [] args) {
int iChoice=int.Parse(args[0]);
delGreeting [] arrayofGreetings={
new delGreeting(Greetings.DisplayEnglish),
new delGreeting(Greetings.DisplayItalian),
new delGreeting(Greetings.DisplaySpanish)};
arrayofGreetings[iChoice-1]();
}
}
}
But this doesn't show me exactly the advantages of using delegates rather than a conditional "If ... { }" that parses the argument and run the method.
Does anyone know why it's better to use delegate here rather than "if ... { }". Also do you have other examples that demonstrate the usefulness of delegates.
Thanks!
Delegates are a great way of injecting functionality into a method. They greatly help with code reuse because of this.
Think about it, lets say you have a group of related methods that have almost the same functionality but vary on just a few lines of code. You could refactor all of the things these methods have in common into one single method, then you could inject the specialised functionality in via a delegate.
Take for example all of the IEnumerable extension methods used by LINQ. All of them define common functionality but need a delegate passing to them to define how the return data is projected, or how the data is filtered, sorted, etc...
The most common real-world everyday use of delegates that I can think of in C# would be event handling. When you have a button on a WinForm, and you want to do something when the button is clicked, then what you do is you end up registering a delegate function to be called by the button when it is clicked.
All of this happens for you automatically behind the scenes in the code generated by Visual Studio itself, so you might not see where it happens.
A real-world case that might be more useful to you would be if you wanted to make a library that people can use that will read data off an Internet feed, and notify them when the feed has been updated. By using delegates, then programmers who are using your library would be able to have their own code called whenever the feed is updated.
Lambda expressions
Delegates were mostly used in conjunction with events. But dynamic languages showed their much broader use. That's why delegates were underused up until C# 3.0 when we got Lambda expressions. It's very easy to do something using Lambda expressions (that generates a delegate method)
Now imagine you have a IEnumerable of strings. You can easily define a delegate (using Lambda expression or any other way) and apply it to run on every element (like trimming excess spaces for instance). And doing it without using loop statements. Of course your delegates may do even more complex tasks.
I will try to list some examples that are beyond a simple if-else scenario:
Implementing call backs. For example you are parsing an XML document and want a particular function to be called when a particular node is encountered. You can pass delegates to the functions.
Implementing the strategy design pattern. Assign the delegate to the required algorithm/ strategy implementation.
Anonymous delegates in the case where you want some functionality to be executed on a separate thread (and this function does not have anything to send back to the main program).
Event subscription as suggested by others.
Delegates are simply .Net's implementation of first class functions and allow the languages using them to provide Higher Order Functions.
The principle benefit of this sort of style is that common aspects can be abstracted out into a function which does just what it needs to do (for example traversing a data structure) and is provided another function (or functions) that it asks to do something as it goes along.
The canonical functional examples are map and fold which can be changed to do all sorts of things by the provision of some other operation.
If you want to sum a list of T's and have some function add which takes two T's and adds them together then (via partial application) fold add 0 becomes sum. fold multiply 1 would become the product, fold max 0 the maximum. In all these examples the programmer need not think about how to iterate over the input data, need not worry about what to do if the input is empty.
These are simple examples (though they can be surprisingly powerful when combined with others) but consider tree traversal (a more complex task) all of that can be abstracted away behind a treefold function. Writing of the tree fold function can be hard, but once done it can be re-used widely without having to worry about bugs.
This is similar in concept and design to the addition of foreach loop constructs to traditional imperative languages, the idea being that you don't have to write the loop control yourself (since it introduces the chance of off by one errors, increases verbosity that gets in the way of what you are doing to each entry instead showing how you are getting each entry. Higher order functions simply allow you to separate the traversal of a structure from what to do while traversing extensibly within the language itself.
It should be noted that delegates in c# have been largely superseded by lambdas because the compiler can simply treat it as a less verbose delegate if it wants but is also free to pass through the expression the lambda represents to the function it is passed to to allow (often complex) restructuring or re-targeting of the desire into some other domain like database queries via Linq-to-Sql.
A principle benefit of the .net delegate model over c-style function pointers is that they are actually a tuple (two pieces of data) the function to call and the optional object on which the function is to be called. This allows you to pass about functions with state which is even more powerful. Since the compiler can use this to construct classes behind your back(1), instantiate a new instance of this class and place local variables into it thus allowing closures.
(1) it doesn't have to always do this, but for now that is an implementation detail
In your example your greating are the same, so what you actually need is array of strings.
If you like to gain use of delegates in Command pattern, imagine you have:
public static void ShakeHands()
{ ... }
public static void HowAreYou()
{ ... }
public static void FrenchKissing()
{ ... }
You can substitute a method with the same signature, but different actions.
You picked way too simple example, my advice would be - go and find a book C# in Depth.
Here's a real world example. I often use delegates when wrapping some sort of external call. For instance, we have an old app server (that I wish would just go away) which we connect to through .Net remoting. I'll call the app server in a delegate from a 'safecall ' function like this:
private delegate T AppServerDelegate<T>();
private T processAppServerRequest<T>(AppServerDelegate<T> delegate_) {
try{
return delegate_();
}
catch{
//Do a bunch of standard error handling here which will be
//the same for all appserver calls.
}
}
//Wrapped public call to AppServer
public int PostXYZRequest(string requestData1, string requestData2,
int pid, DateTime latestRequestTime){
processAppServerRequest<int>(
delegate {
return _appSvr.PostXYZRequest(
requestData1,
requestData2,
pid,
latestRequestTime);
});
Obviously the error handling is done a bit better than that but you get the rough idea.
Delegates are used to "call" code in other classes (that might not necessarily be in the same, class, or .cs or even the same assembly).
In your example, delegates can simply be replaced by if statements like you pointed out.
However, delegates are pointers to functions that "live" somewhere in the code where for organizational reasons for instance you don't have access to (easily).
Delegates and related syntactic sugar have significantly changed the C# world (2.0+)
Delegates are type-safe function pointers - so you use delegates anywhere you want to invoke/execute a code block at a future point of time.
Broad sections I can think of
Callbacks/Event handlers: do this when EventX happens. Or do this when you are ready with the results from my async method call.
myButton.Click += delegate { Console.WriteLine("Robbery in progress. Call the cops!"); }
LINQ: selection, projection etc. of elements where you want to do something with each element before passing it down the pipeline. e.g. Select all numbers that are even, then return the square of each of those
var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
.Where(delegate(int x) { return ((x % 2) == 0); })
.Select(delegate(int x) { return x * x; });
// results in 4, 16, 36, 64, 100
Another use that I find a great boon is if I wish to perform the same operation, pass the same data or trigger the same action in multiple instances of the same object type.
In .NET, delegates are also needed when updating the UI from a background thread. As you can not update controls from thread different from the one that created the controls, you need to invoke the update code withing the creating thread's context (mostly using this.Invoke).

Categories