MacMusic  |  PcMusic  |  440 Software  |  440 Forums  |  440TV  |  Zicos
extension
Recherche

How to use extension methods in C#

jeudi 3 octobre 2024, 11:00 , par InfoWorld
In the C# programming language, extension methods enable you to extend the functionality of existing types without modifying them or deriving new types from them using inheritance. You don’t need to create subclasses of existing classes or recompile or modify your existing classes to use extension methods. Extension methods improve the readability of your code while at the same time allowing you to extend the functionality of existing classes or interfaces. Microsoft introduced extension methods in C# 3.0.

Common extension methods in.NET include the LINQ standard query operators that add additional query capabilities to the System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types. Note that you can take advantage of extension methods not only to extend a class or an interface but you cannot override their methods. Microsoft’s documentation states:

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

Essentially, an extension method is a special type of static method that allows you to add functionality to an existing type even if you don’t have access to the source code of the type. An extension method is just like another static method but always includes the “this” reference as its first parameter. You can add as many extension methods as you want to any type. Most importantly, you can even add extension methods to a value type.

Let’s examine how we can make use of extension methods in C#.

Create a console application project in Visual Studio

First off, let’s create a.NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new.NET Core console application project.

Launch the Visual Studio IDE.

Click on “Create new project.”

In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.

Click Next.

In the “Configure your new project” window, specify the name and location for the new project.

Click Next.

In the “Additional information” window shown next, choose “.NET 8.0 (Long Term Support)” as the framework version you would like to use.

Click Create.

We’ll use this.NET 8 console application project to work with the code examples shown in the subsequent sections of this article.

Define an extension method in C#

Extension methods are a feature of the C# programming language that enable you to extend functionality to a type without inheriting from the type, recompiling the code, or modifying the original type. To define an extension method in C#, follow these steps:

Create a class in C# and use the “static” keyword to mark the class as static.

Define a static method inside the class, i.e., a method that has the “static” keyword specified in the method signature.

Ensure that the first parameter of this static class accepts the “this” reference.

The following is an example of a typical C# class named MyExampleClass that contains an instance method named MyExampleMethod. This class is followed by a static class called MySampleClassExtensions that extends the functionality of the instance method. Note that the static class MySampleClassExtensions contains an extension method named MyExampleExtensionMethod that accepts the “this” reference as the first parameter of the method.

public class MyExampleClass
{
    public void MyExampleMethod()
    {
        Console.WriteLine('This is an instance method.');
    }
}
public static class MyExampleClassExtensions
{
    public static void MyExampleExtensionMethod(this MyExampleClass obj)
    {
        Console.WriteLine('This is an extension method.');
    }
}

You can use the following piece of code to invoke the extension method.

MyExampleClass myClass = new MyExampleClass();
myClass.MyExampleExtensionMethod();

When you execute the above piece of code, the text “This is an extension method” will be displayed at the console as shown in Figure 1.

Figure 1
IDG

Note that if you define an extension method with a signature identical to that of an instance method, the instance method will always take precedence. The extension method will never be called.

Using extension methods to extend existing types

You can take advantage of extension methods to add additional functionality — integers, strings, chars, etc. — to existing types in C#. For example, the code snippet below illustrates how you can extend the string class in C# to add a new method that returns the count of non-space characters in the string.

public static class MyStringExtensions
{
    public static int CountNonSpaceCharacters(this string input)
    {
        return new string(input.ToCharArray()
      .Where(c =>!Char.IsWhiteSpace(c))
      .ToArray()).Length;
    }
}

The following code snippet shows how you could use the CountNonSpaceCharacters extension method.

string str = 'This is a test string';
Console.WriteLine('The number of non-space characters in the string is: '+str.CountNonSpaceCharacters());
Console.Read();

Figure 2 shows the output when you run the preceding piece of code.

Figure 2IDG

Here’s another example of an extension method. This extension method extends the List class in C#.

public static class MyListExtensions
{
    public static T GetLastElement(this List list)
    {
        if(list.Count > 0)
            return list[list.Count - 1];
        return default(T);
    }
}

The GetLastElement is an extension method that returns the last element of a list. You can invoke this extension method using the following code snippet.

List integers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int element = integers.GetLastElement();
Console.WriteLine(element);

Overloading an extension method in C#

Similar to other methods, you can also overload an extension method. The following code snippet shows how you can overload the Substring method of the string class to return a substring of a string. This overloaded Substring method takes the starting and ending index and a Boolean as parameters. The Boolean denotes if the returned string should be converted to upper case. If you pass true in this parameter when calling the extension method, the returned string will be converted to upper case.

public static string Substring(this string str, int startIndex,
int endIndex, bool convertToUpper)
{
    string result = str.Substring(startIndex, endIndex - startIndex);
    if (convertToUpper)
    {
        return result.ToUpper();
    }
    return result;
}

You can call the preceding extension method by using the following code snippet.

string str = 'Hello World!';
string result = str.Substring(6,11, true);
Console.WriteLine(result);

When you run the program, the text “World” will be displayed at the console window as shown in Figure 3.

Figure 3
IDG

Extending an interface in C#

Extension methods can be used to add additional functionality to interfaces as well. To do this, create an extension method in C# that can accept an interface as its first argument. Consider the following interface called IMyInterface.

public interface IMyInterface
{
    public void MyMethod();
}

The MyClass class below implements the IMyInterface.

public class MyClass: IMyInterface
{
    public void MyMethod()
    {
        Console.WriteLine('This is an instance method.');
    }
}

Interestingly, most LINQ methods are based on extension methods. For example, the standard query operators in LINQ — i.e., select, where, etc. — are implemented in the C# class named Enumerable. Each of these methods is implemented as an extension method pertaining to the IEnumerable interface.

Working with extension methods in C#

Here are a few important points you should remember regarding extension methods in C#:

Extension methods of a class must be static.

The first argument of an extension method must be a reference to the type on which the extension method is to be invoked.

Extension methods cannot be used to access private members of a class.

You cannot modify the private state of an object using extension methods.

You can use an extension method to extend an interface or a class but you cannot override them.

Extension methods enable you to write code in a more expressive and fluent way. That said, you should not overuse extension methods because they can make your source code more difficult to comprehend. Hence, use extension methods judiciously; never use them only to make your code more concise. Extension methods are not meant for reducing the KLOC — an acronym for thousands of lines of code.
https://www.infoworld.com/article/3543666/how-to-use-extension-methods-in-c-sharp.html

Voir aussi

News copyright owned by their original publishers | Copyright © 2004 - 2024 Zicos / 440Network
Date Actuelle
mer. 18 déc. - 09:59 CET