0

I have a ToString extension method of an IEnumerable, which converts it to a list of strings as follows:

    public static string ToString<T>(this IEnumerable<T> theSource,
                                     string theSeparator) where T : class
    {
        string[] array = 
                     theSource.Where(n => n != null).Select(n => n.ToString()).ToArray();

        return string.Join(theSeparator, array);
    }

I now want to do something similar with an array of enums: given theXStatuses, an array of XStatus enum values, I want to get a string containing the enum values separatd by theSeparator. For some reason, the above extension method doesn't work for XStatus[]. So I tried

        public static string ToString1<T>(this IEnumerable<T> theSource,string theSeparator)
                                                                             where T : Enum

But then I got an error that "cannot use ... 'System.Enum'...as type parameter constraint.

Is there any way to achive this?

1
  • 1
    This is C#, right? You should add that tag to your question (I'd do it but I'm not 100% certain it's C#). Commented Feb 24, 2011 at 13:35

2 Answers 2

4

No cant be done. The closest would be where T : struct and than throw error inside function if not Enum.

Edit: If you remove where T : class from your original function it will work on enums also. Also skip the ToArray() as String.Join takes in IEnumerable<string>

Sign up to request clarification or add additional context in comments.

Comments

2

Magnus is right, it can't be done, elegantly. The limitation can be circumvented with a small hack, like so:

public static string ToString<TEnum>(this IEnumerable<TEnum> source,
                            string separator) where TEnum : struct
{
    if (!typeof(TEnum).IsEnum) throw new InvalidOperationException("TEnum must be an enumeration type. ");
    if (source == null || separator == null) throw new ArgumentNullException();
    var strings = source.Where(e => Enum.IsDefined(typeof(TEnum), e)).Select(n => Enum.GetName(typeof(TEnum), n));
    return string.Join(separator, strings);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.