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
}
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With