Possible Duplicate:
Is it possible to create an extension method to format a string?
I have this class:
public class Person
{
public string Name { get; set; }
public uint Age { get; set; }
public override string ToString()
{
return String.Format("({0}, {1})", Name, Age);
}
}
The extension method:
public static string Format(this string source, params object[] args)
{
return String.Format(source, args);
}
And I want to test it, but I have the following strange behavior:
Person p = new Person() { Name = "Mary", Age = 24 };
// The following works
Console.WriteLine("Person: {0}".Format(p));
Console.WriteLine("Age: {0}".Format(p.Age));
// But this gives me a compiler error:
Console.WriteLine("Name: {0}".Format(p.Name));
The compiler error:
Unable to access member ‘string.Format (string, params object [])’ with a reference to an instance. Qualify it with a type name.
Why? How can I solve this problem?
Since
p.Nameis a string, you have an ambiguous call in the third scenario:vs.
The resolver chooses the method that fits the signature best (in your case a
stringvs. anobject[]) over the extension method.You can solve the problem by either renaming the extension method, or by casting the second parameter to an object to prevent the resolver from choosing the static method: