string.Format extention method
-
Sunday, July 05, 2009 10:33 AMI have wrote following extention method:When i use that method by following way:
public static string Format(this string someString, params object[] args) { return string.Format(someString, args); }
all works fine."String to format {0}".Format(someObject)But when i write:i have compile error:"String to format {0}".Format(someObject.ToString())Member 'string.Format(string, params object[])' cannot be accessed with an instance reference; qualify it with a type name insteadIt is unexpected behaviuor for me.- Edited by Igor Buchelnikov Sunday, July 05, 2009 10:40 AM spelling
All Replies
-
Sunday, July 05, 2009 12:58 PMHello,Igor
You have to cast the string to an object
"String to format {0}"
.Format((object)someObject.ToString())
it will work, and for more infomation you can see the following thread.
http://social.msdn.microsoft.com/Forums/en-US/vcsharp2008prerelease/thread/f15cf05a-72aa-43ee-94ed-19ea465233be
Some report this as Extension Methods bug, and Microsoft investigating this, because it seems to be a consequence of the Extension Methods lookup rules.
Thanks -
Sunday, July 05, 2009 1:18 PMModerator
The string class already has a bunch of overloads for the Format() method, all of which are static methods. You are asking the compiler to resolve the inherent ambiguity between your extension method and the static String.Format(String, Object) method. Somewhat surprisingly, that works when you pass an object. It appears to favor the instance method, picking your extension. But that stops working when it needs to convert the argument from string to object.
The error message you get is certainly quacks like a compiler bug. Report it at connect.microsoft.com. I suspect that after they fix that bug, your first version will no longer compile either. It really should have picked the static method. Which probably means they won't fix the bug, it would break too much existing code. Either way, your extension method is doomed.
Just give it a different name. How about Paste()?
Hans Passant.- Marked As Answer by Zhi-Xin Ye Friday, July 10, 2009 12:52 PM
-
Sunday, July 05, 2009 7:38 PMI have renamed my extention method to FormatWith().But it is not nice solution, therefore i hope Microsoft will teach C# compiler to differentiate instance and static methods with same signatures by their calling way. In http://social.msdn.microsoft.com/Forums/en-US/vcsharp2008prerelease/thread/f15cf05a-72aa-43ee-94ed-19ea465233be it can be seen that root of the problem just this. I'm looking forward to get fix in C# 4.0 !
- Edited by Igor Buchelnikov Sunday, July 05, 2009 8:03 PM clarification
-
Sunday, July 05, 2009 8:01 PMModeratorIt is not fixed in C# 4.0 beta, exact same error message. You'd better hurry up with the feedback report if you want it fixed.
Hans Passant.

