views:

49

answers:

1

Hi!

I've added an extension method that is a shortcut to string.Format:

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

When I invoke this method like this:

"{0}".Format(1);

everything works like a charm. While

"{0}".Format("1"); 

does not compile with this error message:

error CS0176: Member 'string.Format(string, params object[])' cannot be accessed with an instance reference; qualify it with a type name instead

I fixed this issue by renaming a method (ooh it was a pain). But why does it happen? I know about extension vs instance priority - but this is not an instance method. And IMO if one path could not be resolved (referencing static method in non-static context) then the other (fully legitimate) should be attempted. What do I miss in spec?

Update 1 Added compile error message.

+2  A: 

Section 7.5.3.1 (function member applicability) says nothing about whether a member is static or not. In other words, the static method String.Format(String, params Object[] args) is still applicable in your second invocation, even though it won't actually work.

Extension methods are only searched for if no applicable function members are found.

In other words, member lookup is performed on a type and a set of arguments (and potentially type arguments). The validation of the result of the member lookup is done later, as the final step of section 7.6.5.1.

Jon Skeet
If applicable!=compilable - then it's logical. I agree. It would be better if such shortcuts worked, though :).
Nikolay R