davewilliams459
davewilliams459

Reputation: 1739

Extension method using non Instantiated object, i.e. String.F()

At a previous organization, we implemented an extension method that created a shorthand for String.Format. The method was called "String.F". However I do not seem to be able to get this to work. A former co-worker gave me the following code which I am listing below along with my own test method. In the function 'Test()', "String.F" throws and error and is not displayed in intellisence. I would ask if this is not possible, but I have writen code using a call to this method. Is this only possilble when using an instantiated string? Thanks.

public static class MyExtensions {
    public static string F(this string target, params object[] args) {
        return "hello";
    }
}

class TestExtensions {
    public string Test() {
        return String.F("test:{0}", "test");
    }
}

Upvotes: 1

Views: 368

Answers (2)

Steven
Steven

Reputation: 1280

I think the problem is you're invoking String.F, when the class that owns the method is MyExtensions; not String...if you want to invoke it like that, it should be MyExtensions.F("test{0}", "test")

As others have mentioned, though, while this is perfectly valid, it seems to be sidestepping the very thing that makes extension methods distinct.

Doing "test{0}".F("test"); should give the same result as MyExtensions.F("test{0}", "test"); If F wasn't set up as an extension method, only the latter approach would be valid.

Upvotes: 1

Bala R
Bala R

Reputation: 109037

You cannot do extension method and use it in a static context. Extension methods can be used only as instance methods.

You can do

public static string F(this string target, params object[] args) {
        return String.Format(target, args);
}

and use it like this

"test:{0}".F("test");

Upvotes: 6

Related Questions