How to fix Code Analysis warning CS8605 when using foreach with Enum.GetValues()?

Viewed 960

Consider the following .Net Core 3.1 code:

using System;

namespace CoreConsoleA
{
    public static class Program
    {
        static void Main()
        {
            // Warning CS8605, Unboxing a possibly null value:
            foreach (MyEnum enumValue in Enum.GetValues(typeof(MyEnum))) 
            {
                Console.WriteLine(enumValue);
            }
        }
    }

    enum MyEnum { Zero, One, Two };
}

With Code Analysis and nullable checking turned on, the code above elicits "Warning CS8605 Unboxing a possibly null value."

I can suppress the warning using "#pragma warning disable CS8605".

I can also write the code like so:

foreach (MyEnum? enumValue in Enum.GetValues(typeof(MyEnum)))
{
    Console.WriteLine(enumValue!.Value);
}

but that seems a bit weird, given that Enum.GetValues(typeof(MyEnum)) can't possibly return any nulls.

Is there a better way to address this issue?

1 Answers

(Answering my own question, since I just realised what I should be doing!)

You can just cast the return value of Enum.GetValues() to the correct type, like so:

foreach (var enumValue in (MyEnum[]) Enum.GetValues(typeof(MyEnum)))
{
    Console.WriteLine(enumValue);
}
Related