What is Extension Method in C# and how to use them?
What is Extension Method in C# and how to use them?
Extension methods in C# are a special kind of static method that allow you to "extend" or add new methods to existing types without creating a new derived type, recompiling, or modifying the original type. They provide a way to add functionality to a type in a static and reusable way.
To define an extension method, you need to:
this keyword.Here's an example:
public static class StringExtensions
{
public static string Reverse(this string str)
{
return new string(str.Reverse().ToArray());
}
}
In this example, we define a static class called StringExtensions that contains an extension method called Reverse. The first parameter of the Reverse method is string, preceded by the this keyword, indicating that it is an extension method for the string type.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.