Udostępnij za pośrednictwem


How to: Implement and Call a Custom Extension Method (C# Programming Guide)

This topic shows how to implement your own extension methods for any type in the .NET Framework Class Library, or any other .NET type that you want to extend. Client code can use your extension methods by adding a reference to the DLL that contains them, and adding a using directive that specifies the namespace in which the extension methods are defined.

To defining and call the extension method

  1. Define a static class to contain the extension method.

    The class must be visible to client code. For more information about accessibility rules, see Access Modifiers (C# Programming Guide).

  2. Implement the extension method as a static method with at least the same visibility as the containing class.

  3. The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.

  4. In the calling code, add a using directive to specify the namespace that contains the extension method class.

  5. Call the methods as if they were instance methods on the type.

    Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.

Example

The following example implements an extension method named WordCount in the MyExtensions.StringExtension class. The method operates on the String class, which is specified as the first method parameter. The MyExtensions namespace is imported into the application namespace, and the method is called inside the Main method.

using System.Linq;
using System.Text;
using System;

namespace CustomExtensions
{
    //Extension methods must be defined in a static class 
    public static class StringExtension
    {
        // This is the extension method. 
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined. 
        public static int WordCount(this String str)
        {
            return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
namespace Extension_Methods_Simple
{
    //Import the extension method namespace. 
    using CustomExtensions;
    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            //  Call the method as if it were an  
            //  instance method on the type. Note that the first 
            //  parameter is not specified by the calling code. 
            int i = s.WordCount();
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}

Compiling the Code

To run this code, copy and paste it into a Visual C# console application project that has been created in Visual Studio. By default, this project targets version 3.5 of the .NET Framework, and it has a reference to System.Core.dll and a using directive for System.Linq. If one or more of these requirements are missing from the project, you can add them manually. For more information, see How to: Create a LINQ Project.

Security

Extension methods present no specific security vulnerabilities. They can never be used to impersonate existing methods on a type, because all name collisions are resolved in favor of the instance or static method defined by the type itself. Extension methods cannot access any private data in the extended class.

See Also

Concepts

C# Programming Guide

Reference

Extension Methods (C# Programming Guide)

Static Classes and Static Class Members (C# Programming Guide)

protected (C# Reference)

internal (C# Reference)

public (C# Reference)

this (C# Reference)

namespace (C# Reference)

Other Resources

Language-Integrated Query (LINQ)