Domanda

Is it possible to create an extension method that takes no parameters? I am new to using extension methods and have only seen them using parameters.

From RB Whitaker's C# tutorial:

public static class StringExtensions
{
    private static Random random = new Random();

    public static string ToRandomCase(this string text)
    {
        string result = "";

        for (int index = 0; index < text.Length; index++)
        {
            if (random.Next(2) == 0)
            {
                result += text.Substring(index, 1).ToUpper();
            }
            else
            {
                result += text.Substring(index, 1).ToLower();
            }                
        }

        return result;
    }
}

And also from MSDN:

"Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier."

Both of these, and especially the code examples on each site (only one posted here), seem to indicate that extension methods must have at least one parameter, because that parameter is used to attach the this keyword to, allowing the method to register as an extension to the class or type which follows it. For example,

public static StringExtension(this String a) {/*stuff*/}

(If this is the case, then that also means that the first parameter in an extension method must accept an instance of the class it's extending, so I am probably wrong.)

È stato utile?

Soluzione

That's correct. Extension methods require at least one parameter, marked with the this modifier.

However, when invoking the extension method with a reference to the class you're extending, you wouldn't specify the parameter:

"foo".StringExtension();

Is equivalent to:

StringExtensions.StringExtension("foo");

Even if you don't actually use the parameter within your method, declaring it is necessary in order to use the syntax provided by extension methods.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top