12

I was using LinqPad to test out some Enum functions and I didn't get integers like I expected when I used .Dump(). Why did the ToList() solve the problem?

void Main()
{
    Enum.GetValues(typeof(Options)).Cast<int>().Dump();
    Enum.GetValues(typeof(Options)).Cast<int>().ToList().Dump();
}

public enum  Options 
{
   Equal,
   LessThan,
   GreaterThan
}

enter image description here

1
  • i think this is a limitation of the .Cast operation. Enum.GetValues(typeof(Options)).Cast<int>().Select(f => (int)f).Dump(); works for me. Commented Apr 24, 2014 at 18:44

1 Answer 1

15

Actually, LINQPad is not the culprit here. This is because of an optimization in Enumerable.Cast:

    public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) {
        IEnumerable<TResult> typedSource = source as IEnumerable<TResult>;
        if (typedSource != null) return typedSource;
        if (source == null) throw Error.ArgumentNull("source");
        return CastIterator<TResult>(source);
    }

As you can see, if source implements IEnumerable<TResult>, then Cast just returns the source unchanged. In this case, source is of type Option[], which happens to implement IEnumerable<int>, so Cast returns an array of Option, and LINQPad dumps it.

I must admit that it came as a surprise that Option[] can be cast to IEnumerable<int>, but it seems to be the case...

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

3 Comments

It can't just be cast to IEnumerable<int> - it can be cast to int[]! This is a conversion that the CLR allows, but the C# language doesn't... so to make the cast compile, you have to confuse the C# compiler by converting to object first... but then it works fine.
@JonSkeet, I assume that it works only because the underlying type of that enum is int?
Yup. Although you could cast to uint[] as well. The CLR is quite forgiving when it comes to conversions like that.

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.