Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does LINQPad dump enum integer values as strings?

Tags:

c#

linqpad

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

like image 232
Ryan Avatar asked Apr 24 '14 18:04

Ryan


People also ask

Can an enum be a string?

In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member. While string enums don't have auto-incrementing behavior, string enums have the benefit that they “serialize” well.

What to use instead of enum C#?

A common alternative to string enum in C# is to create a class with constant strings. This is preferable because it makes the intent of each constant clearer, and also allows you to add methods or other extended functionality. A good example of using a static class as an alternative to enum is HttpMethods in NET Core.

How to use enum for string in C#?

An enumeration is a pre-defined set of constant values that a variable can store. The enum class is used to declare an enumeration in C#. By default, the type of variables inside the enum class is int. There is no built-in method of declaring an enumeration with string values.


1 Answers

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...

like image 158
Thomas Levesque Avatar answered Oct 05 '22 07:10

Thomas Levesque