Why use delegates only to access methods? Is there a purpose.. I dont get it. plzz help me understand this
Why use delegates only to access methods? Is there a purpose.. I dont get it. plzz help me understand this
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Suthish NairPosted Mar 3, 2011, 1:31 PM
A delegate is a reference to a method, the caller has no need access other properties,
methods, or interfaces on the object implementing the method.
Purpose of Delegates in C#
VulpesPosted Mar 3, 2011, 6:31 AM
1. Delegates enable you to write code which is more generic. For example, if you declare a method parameter to be of a particular delegate type, then you can pass ANY compatible method as an argument to the method so that it can be called within the body of that method.
2. Delegates are multi-cast which means that you can call not just one, but several, compatible methods with just a single delegate call. The methods to be called are stored in the delegate's 'invocation list'.
Also, when calling unmanaged functions from managed code, delegates provide a bridge between C function pointers and .NET methods which can be used to enable the unmanaged function to call back the latter.
However, the main reason for including delegates in .NET is because they are the basis of events. Events are just a special type of delegate which only allow outside code (i.e. code outside the class in which the event is declared) to add methods to, or remove them from, the event's invocation list. In C# this is done using the special operators += and -= respectively.
Events are more secure than ordinary delegates because, apart from these operations, outside code is unable to examine or manipulate the event's invocation list.
Jaganathan BantheswaranPosted Mar 3, 2011, 1:29 AM
Hi,
Basically it is similar like the old "C" - function pointer, where functions can be assigned like a variable and called in the run time based on dynamic conditions. C# delegate is the smarter version of function pointer which helps software architects a lot, specially while utilizing design patterns.
At first, a delegate is defined with a specific signature (return type, parameter type and order etc). To invoke a delegate object, one or more methods are required with the EXACT same signature. A delegate object is first created similar like a class object created. The delegate object will basically hold a reference of a function. The function will then can be called via the delegate object.
Refer this article. http://www.c-sharpcorner.com/UploadFile/subhendude/4621/