Search code examples
c#lambdaenumsintstring-formatting

How do I cast an Enum to its underlying type BEFORE calling instance method, in one line?


I ran across the need for this answer when attempting to try:

(int)myEnum.ToString("D2");

This doesn't work, because it thinks I'm trying to cast the string return value from .ToString("D2")

Of course it's easy enough to do:

var myInt = (int)myEnum;
myInt.ToString("D2");

BUT, I want to know if a one line solution exists so that I can use this in a lambda i.e.

// Assuming this worked how I wanted it to
myEnums.Select(myEnum => (int)myEnum.ToString("D2"))

Goal here is to transform my IEnumerable of myEnum into left zero-padded ints


Solution

  • You have to add another pair of parentheses:

    var x = ((int)myEnum).ToString("D2");
    

    i. e. your linq query would look like this:

    var x = myEnums.Select(myEnum => ((int)myEnum).ToString("D2"));