I want to know the difference between using Delegate Methods and using General Methods[without Delegates].
For Example :
With Delegate :
delegate void DelMethod(string str);
static void Method(string str)
{
Debug.WriteLine(str);
}
Usage :
DelMethod dm = new DelMethod(Method);
dm(string);
And Without Delegate :
static void Method(string str)
{
Debug.WriteLine(str);
}
Usage :
Method(string)
What are the differences of these two??
The method without delegate is smaller and easy. But I find coders using delegated Methods frequently.
What is the reason behind this??
Delegates are for another situation. Imagine, that you have a class which should answer for something from another class, but you know nothing about the second class. In such situation you can do a Delegate in the first.
Class A
knows nothing aboutclass B
, but it can call B's methods and get it's results. TheAnswer
method inclass B
is private andclass A
can't call it directly.Read more in MSDN
Another use of delegates:
Without the presence of delegates, only the class defining your private methods would be able to call those methods. With wrapping of methods inside a delegate, you could pass your delegate instance to other classes and let them invoke the delegate (as a callback) with the proper parameters and that would eventually call your actual private method within the defining class.
For Example :
In general MSDN has following to say at This article :
Delegates are useful when:
Imagine a scenario in which you have a function that searches a Customer. Initially you just want to search by name so you write something like:
Then your specifications change and you have to implement new ways of searching (let's say "search-by-address"). No problem, we refactor our old code to:
They look very similar, don't they?
Now your boss tell again you to add another search functionality, the user may want to find customers by telephone number. It is getting boring, isn't it?
Fortunately developers have found a way to make other developers' life easier inventing delegates. Using them you could create one bigger, general function that helps you to avoid rewriting the same pieces of code again and again.
Now you do not have to create a specialized function each time you need a new way of searching customers, so you can write:
Delegates are also useful to manage events and are used intensively also in LINQ. Just google "delegates c#" and you will discover a huge new world! :)
There is one particular scenario where the two calls will differ, ie when it comes to optional arguments. Consider these
But
In the first case, it is the optional argument of the delegate that is inserted at the call site.