A delegate in C# is a type-safe, object-oriented function pointer. It can be used to refer to a method in C# and pass it as a parameter to a method. This allows methods to be passed around and executed dynamically at runtime. Delegates are often used for events and callbacks in C#, as they provide a way for a method to be invoked when an event occurs.
Here's a simple example of how delegates can be used in C#:
There are several types of delegates in C#:
Here's a simple example of how delegates can be used in C#:
delegate int MyDelegate(int a, int b);
class Program
{
static void Main(string[] args)
{
MyDelegate sumDelegate = new MyDelegate(Add);
int result = sumDelegate(5, 10);
Console.WriteLine("Result: " + result);
}
static int Add(int a, int b)
{
return a + b;
}
}
In this example, the `MyDelegate` delegate is defined to refer to methods that take two `int` parameters and return an `int` result. The `sumDelegate` variable is then created as an instance of `MyDelegate` that references the `Add` method. Finally, the `sumDelegate` is invoked, which in turn invokes the `Add` method and returns the result.Delegates in C# are type-safe, meaning that they can only refer to methods that match their signature. This ensures that the correct method is called at runtime. Delegates can also be combined together to create multicast delegates, which can refer to and invoke multiple methods at once.
- Single Delegate: Refers to a single method. It is the simplest type of delegate.
- Multicast Delegate: Refers to multiple methods. When a multicast delegate is invoked, all of the methods it references are invoked in the order in which they were added to the delegate.
- Anonymous Delegate: A delegate that is defined inline without a named method. It is often used for simple delegates that are only used in a single location.
- Func Delegate: A delegate that is defined by the Func class in the .NET framework. It is used to represent a method that returns a value.
- Action Delegate: A delegate that is defined by the Action class in the .NET framework. It is used to represent a method that does not return a value.
- Predicate Delegate: A delegate that is defined by the Predicate class in the .NET framework. It is used to represent a method that returns a Boolean value indicating whether a condition is true or false.
Comments
Post a Comment