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.
Once you have defined an extension method, you can call it on any instance of the type you extended, as if it were a regular instance method. Here's an example:
string myString = "Hello, World!";
string reversedString = myString.Reverse();
In this example, we call the Reverse
extension method on the ...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào