What's the best way to get rid of this code duplication in C#? #5592
-
I have an extension method:
I have an I cannot call I could do this:
However now, for every I tried to make an implicit conversion:
However that generated a compile error - apparently interfaces cannot have implicit conversions. For now I've made this extension method:
And then I do this:
However there's still code duplication because I may have to type Besides writing code that generates C# code, I cannot think of a way to get rid of the code duplication. What's the best way to get rid of this code duplication in C#? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
public static string StringJoin(this IEnumerable<string> strings, string separator)
{
string[] array = strings.ToArray();
return string.Join(separator, array);
} This is not necessary, |
Beta Was this translation helpful? Give feedback.
-
public static string StringJoin(this IEnumerable<char> chars, string separator)
{
return chars.Select(c => c.ToString()).StringJoin(separator);
} Instead of that, do: public static string StringJoin<T>(this IEnumerable<T> chars, string separator)
{
return chars.Select(c => c.ToString()).StringJoin(separator);
} That said, as with teh first comment, |
Beta Was this translation helpful? Give feedback.
-
Could also do this, which takes advantage of the existing using System.Collections.Generic;
public static class StringExtensions {
public static string StringJoin<T>(this IEnumerable<T> values, string separator) {
return string.Join(separator, values);
}
} |
Beta Was this translation helpful? Give feedback.
Instead of that, do:
That said, as with teh first comment,
string
already has an overload for this.