Câu hỏi phỏng vấn C#
Câu hỏi

What is Extension Method in C# and how to use them?

Câu trả lời

Extension Methods in C#

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.

How to Define Extension Methods

To define an extension method, you need to:

  1. Create a static class to hold the extension method(s).
  2. Define the extension method as a static method within the static class.
  3. The first parameter of the extension method must be the type you want to extend, preceded by the this keyword.

Here's an example:

csharp Copy
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.

Using Extension Methods

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:

csharp Copy
string myString = "Hello, World!";
string reversedString = myString.Reverse();

In this example, we call the Reverse extension method on the ...

middle

middle

Gợi ý câu hỏi phỏng vấn

expert

Can you add extension methods to an existing static class?

junior

What is the difference between string and StringBuilder in C#?

junior

What is namespace in C#?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào