Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an extension method to format a string?

the question is really simple. How do we format strings in C#? this way:

 string.Format("string goes here with placeholders like {0} {1}", firstName, lastName);

Now, is it possible to create an extension method to do it this way?

 "string goes here {0} {1}".Format(firstName, lastName);

That's all.

like image 320
Saeed Neamati Avatar asked Jul 05 '11 18:07

Saeed Neamati


1 Answers

Well, it's more complicated than it looks. Others say this is possible, and I don't doubt them, but it doesn't seem to be the case in Mono.

There, the standard overloads of the Format() method seem to take precedence in the name resolution process, and compilation fails because a static method ends up being called on an object instance, which is illegal.

Given this code:

public static class Extensions
{
    public static string Format(this string str, params object[] args)
    {
        return String.Format(str, args);
    }
}

class Program
{
    public static void Main()
    {
        Console.WriteLine("string goes here {0} {1}".Format("foo", "bar"));
    }
}

The Mono compiler (mcs 2.10.2.0) replies with:

foo.cs(15,54): error CS0176: Static member `string.Format(string, object)' cannot be accessed with an instance reference, qualify it with a type name instead

Of course, the above compiles cleanly if the extension method is not named Format(), but maybe you actually want to use that name. If that's the case, then it's not possible, or at least not on all implementations of the .NET platform.

like image 166
Frédéric Hamidi Avatar answered Oct 16 '22 21:10

Frédéric Hamidi