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:

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:

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

senior

What is the difference between System.ApplicationException class and System.SystemException class?

senior

What happens when we Box or Unbox Nullable types?

senior

Can you create a function in C# which can accept varying number of arguments?

Bình luận

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

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