Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method for string array and params

How can I get both these two methods to compile?

public static IEnumerable<string> DoSomething(params string[] args)
{ // do something }
public static IEnumerable<string> DoSomething(this string[] args)
{ // do something }

I get this compile error:

Type 'Extensions' already defines a member called 'DoSomething' with the same parameter types Extensions.cs

So that I can do this:

new string[] { "", "" }.DoSomething();
Extensions.DoSomething("", ""); 

Without the params method, I have to do this:

Extensions.DoSomething(new string[] { "", "" });

Update: Based on the answer by O. R. Mapper

public static IEnumerable<string> DoSomething(string arg, params string[] args)
{
    // args null check is not required
    string[] argscopy = new string[args.Length + 1];
    argscopy[0] = arg;
    Array.Copy(args, 0, argscopy, 1, args.Length);
    return argscopy.DoSomething();
}

Update: I like HugoRune's answer now.

like image 513
hIpPy Avatar asked Nov 27 '12 22:11

hIpPy


2 Answers

You can add an additional parameter to the params version:

public static IEnumerable<string> DoSomething(string firstArg, params string[] moreArgs)

That should be sufficient for the compiler to distinguish it from the string[] extension method.

As suggested by user SLaks, an additional overload without any arguments should be provided in this case, if the situation with an empty params array needs to be supported:

public static IEnumerable<string> DoSomething()
like image 110
O. R. Mapper Avatar answered Sep 21 '22 20:09

O. R. Mapper


Late answer:

Another option is to just put both methods in different classes. Since you never us the class name when calling the extension method (the one with the this parameter), the extension method can be in any public static class in the same namespace, without any noticeable difference.

// contains static methods to help with strings
public static class StringTools
{
    public static IEnumerable<string> DoSomething(params string[] args)
    {
        // do something
    }
}

// contains only extension methods
public static class StringToolsExtensions
{
    public static IEnumerable<string> DoSomething(this string[] args)
    {
        return StringTools.DoSomething(args);
    }
}

This way you avoid copying the string array, you do not need an additional overload with no arguments, and I would say it looks cleaner. I would always separate extension methods and other static methods to avoid confusion.

like image 44
HugoRune Avatar answered Sep 19 '22 20:09

HugoRune