I've previously asked a question of about Delegates does anyone have a must have scenario where I would have to use a delegate? How does this improve my C# code?
Just as many scenarios I use it in I've always seem to be able to program around it.
I've previously asked a question of about Delegates does anyone have a must have scenario where I would have to use a delegate? How does this improve my C# code?
Just as many scenarios I use it in I've always seem to be able to program around it.
Whenever you're using a Strategy Pattern or an Observer Pattern, delegates make your work much easier than using interfaces.
Nobody mentioned this, but if you are using LINQ with Lambda you use anonymous methods all the time. Which are technically still delegates.
Lets say you have a class called Person
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
And you wanted to implement a find method where you would find the person based on their FirstName
public Person Where(List<Person> list, string firstName)
{
//find the string
foreach(Person item in list)
if(item.FirstName.Equals(firstName))
return item;
}
This is a very specific search and not very dynamic, meaning if you wanted to search by LastName you would have to change this method or write a new one.
Luckily LINQ provides an extension method called Where to which you need to pass a delegate, which you can create on the fly with the help of anonymous methods.
for instance
string searchString = "Stan";
list.Where( person => person.FirstName.Equals(searchString));
but if you wanted to change to search by LastName you would simply do this
string searchString = "R";
list.Where( person => person.LastName.Equals(searchString));
This example might be not what you were looking for, but I just wanted to show that sometimes we use delegates all the time without thinking about it or realizing it.
Assuming you're not talking about events - of course you can program around it. The point is to make it nicer and cleaner.
protected void Sort()
{
foreach (string key in _dBase.Keys)
{
Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key],
new Comparison<Pair<string, Dictionary<string, T>>>(
delegate(Pair<string, Dictionary<string, T>> a, Pair<string, Dictionary<string, T>> b)
{
if (a == null && b != null)
return 1;
else if (a != null && b == null)
return -1;
else if (a == null && b == null)
return 0;
else
return a.First.CompareTo(b.First);
}));
}
}
Could I do that without an inline delegate? Sure. Would I have a floppy private method in my class that would only be used for this one instance? Yup.
Edit: As mentioned in the comments, you can simplify:
Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key],
new Comparison<Pair<string, Dictionary<string, T>>>(
delegate(Pair<string, Dictionary<string, T>> a, Pair<string, Dictionary<string, T>> b)
{
to
Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key], (a,b) =>
{
If you imagine C# without delegates, you would commonly encounter situations where you have classes or interfaces with one method. The name of that method is redundant. e.g.
public interface IGetMail
{
Mail JustGetTheMail();
}
The interface is all about that one method. A reference to an object of that type is really no more than a reference to a single callable method. The calling code:
Mail m = getMail.JustGetTheMail();
could be abreviated to:
Mail m = getMail();
The compiler could do that as "syntactic sugar" without any ambiguity, because there's only one method you could possible call on that getMail
reference.
So let's add that feature to our C# compiler. Now, when declaring these types, we could make that a little neater as well. We don't need to specify the method name when calling it, so why should we have to give the method a name in the first place?
Let's pick a standard method name, Invoke
, i.e.
public interface IGetMail
{
Mail Invoke();
}
We'll add some more syntactic sugar to allow us to write that as:
public delegate Mail GetMail();
Hey presto. We've added delegates to our C# compiler.
(Technically the CLR is also aware of delegates, and so rather than generating an interface, the C# compiler generates a special "delegate" type, which has support for asynchronous invocation, and manipulating an immutable list of delegates and treating them as a single reference; but in a basic form it could have been done with interfaces. There is a proposal to do that for Java).
We can then go further and add anonymous delegates - making them succinct to implement in a way that interfaces are not.
So to answer your question - any time where your interface has one method, it could be a delegate, and you'll be able to seriously cut down the amount of junk code you have to write.
Real World Usage:
3.Now, in a new Win Form , when you drag in Checker...and your objective is to make sure that when chkA is clicked you have to change the background color of a label...lblColorPicker.
Mind you lblColorPicker is a control that exists in the form and is not directly bound to Checker.
How will you achieve this?
Answer:
This way you can control chkA...through the new event from any new form by referencing the event...through a delegate you just wrote.
So, much for Real-World usage!
This objective CANNOT be achieved with out writing the delegate.
Let me know if you think otherwise...or if you need more elaboration.
Anonymous delegates make the code much more readable in some case (you don't have to go to another method to see code that belongs to your method:
Winforms example
class MyForm:Form{
//...
protected override void OnLoad(EventArg e){
this.Cursor=Cursors.Wait();
this.Enabled=false;
// do a long running DB operation without blocking the UI Thread
ThreadPool.QueueUserWorkItem(state=>{
DoLongDBOperation();
// re enable the form
BeginInvoke(new Action(()=>{ this.Cursor=Cursors.Default;this.Enabled=true;}));
});
}
Delegates are an absolute must-have if you add events to your class or are doing anything asynchroneous (There are several other good reasons to have delegates). Benefits is that it is a very flexible approach.
I think you are referring to defining custom delegates?
EventHandler has minimised the requirement for custom delegate definitions but they are still useful if you want to add additional parameters to the method signature.
Whenever you need to modify or change any properties of a winForms control, you need to use a delegate to pass control back to the thread the control was created on... to name just one of many examples.
One example would be a pub/sub message dispatcher. You would need to register the events with the dispatcher and then call them appropriately. This allows you to connect disparate pieces of your code quite easily. I can't think of a way to do this without using delegates
Say you have a console application that responds to different key presses:
Action a = () => {/* Do Stuff*/};
Action b = () => {/* Do Stuff*/};
Action c = () => {/* Do Stuff*/};
Action d = () => {/* Do Stuff*/};
Action e = () => {/* Do Stuff*/};
Action f = () => {/* Do Stuff*/};
Action g = () => {/* Do Stuff*/};
Action h = () => {/* Do Stuff*/};
Action i = () => {/* Do Stuff*/};
Action j = () => {/* Do Stuff*/};
List<Action> actions = new List<Action>() {a,b,c,d,e,f,g,h,i,j};
string line;
while((line = Console.ReadKey().KeyChar) != 'q')
{
if(line.isBetween_0_and_9())
{
actions[line.ParseInt()]();
}
}
You can obviously just use a bunch of Ifs but this not only easier but it's almost certainly more clear/readable.