what is delegate in c

1 year ago 48
Nature

A delegate in C# is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates.

Delegates are similar to function pointers in C and C++ . However, unlike C function pointers, delegates are object-oriented. A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with a lambda expression. Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method is returned to the caller by the delegate. This is known as invoking the delegate.

Delegates are especially useful for implementing events and callback methods. They can be used to reference any method that has a compatible signature and return type. Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. Delegate objects can be composed using the "+" operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed. The "-" operator can be used to remove a component delegate from a composed delegate. Using this property of delegates you can create an invocation list of methods that will be called when a delegate is invoked.