Uncategorized

C# Extension Method

An extension method has simplified calling syntax. It represents static methods as instance methods. An extension method uses the this-keyword in its parameter list. It must be located in a static class.

extension

Example

First, here is a custom extension method defined in a program written in the C# language. Generally, you will want to store your extension method class in a separate source file, such as “ExtensionMethods.cs” in your project.

Note:This file should store a static class with public static extension methods.

Then: In the rest of your source code, you can invoke these extension methods in the same way as instance methods.

using System;

public static class ExtensionMethods
{
    public static string UppercaseFirstLetter(this string value)
    {
    //
    // Uppercase the first letter in the string this extension is called on.
    //
    if (value.Length > 0)
    {
        char[] array = value.ToCharArray();
        array[0] = char.ToUpper(array[0]);
        return new string(array);
    }
    return value;
    }
}

class Program
{
    static void Main()
    {
    //
    // Use the string extension method on this value.
    //
    string value = “dot net perls”;
    value = value.UppercaseFirstLetter(); // Called like an instance method.
    Console.WriteLine(value);
    }
}

In the first part of the program, you can see an extension method declaration in the C# programming language. An extension method must be static and can be public so you can use it anywhere in your source code.

Tip: the extension method is called like an instance method, but is actually a static method. The instance pointer “this” is a parameter.

And: you must specify the this-keyword before the appropriate parameter you want the method to be called upon.

The only difference in the declaration between a regular static method and an extension method is the “this” keyword in the parameter list. If you want the method to receive other parameters, you can include those at the end.

You can call an extension method in the same way you call an instance method. In Visual Studio, an extension method in IntelliSense has a downward arrow on it. This is a visual clue to how methods are represented.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.