I have tried this:
public static class ListHelper
{
public static string ToString<T>(this IList<String> list)
{
return string.Join(", ", list.ToArray());
}
public static string ToString<T>(this String[] array)
{
return string.Join(", ", array);
}
}
But it does not work, both for string[]
and List<string>
. Maybe I need some special annotations?
Simply you Shouldn't use the name
ToString
for the Extension method as it will never be called because that method already exist and you shouldn't useT
as its useless there.For example i tried this and again it returned same thing:
output:
so this time i used
int
and it still ran because that T has no use other then changing the Method Prototype.So simply why are you using
ToString
Literal as Method name, as it already exist and you can't override it in a Extension method, this is the reason you had to use thatT
to make it generic. Use some different name likeThat way you wouldn't have to use generic as it useless there and you could simply call it as always.
That said your code is working for me. here is what i tried (in LINQPAD):
And the output was
shekhar, shekhar, shekhar, shekhar
Since you have specified that
T
inToString<T>
you will need to mention a Type likestring
orint
while calling the ToString method.Extension methods are only checked if there are no applicable candidate methods that match. In the case of a call to
ToString()
there will always be an applicable candidate method, namely, theToString()
onobject
. The purpose of extension methods is to extend the set of methods available on a type, not to override existing methods; that's why they're called "extension methods". If you want to override an existing method then you'll have to make an overriding method.It sounds like you want to replace what
files.ToString()
returns. You will not be able to do that without writing a custom class to assignfiles
as (i.e. inherit from List and overrideToString()
.)First, get rid of the generic type (
<T>
), you're not using it. Next, you will need to rename the extension method because callingfiles.ToString()
will just call the List's ToString method.This does what you're looking for.