0

Purpose is to validate Enum.

namespace Test.Enums
{ 
    public enum Type
    { 
        Audi,
        Porsche,
        Peugeot
    }
}

I would like to write these values into an array so that I can compare them.

[Fact]
public void Test()
{
   //arrange
    string[] expected = {"Audi", "Porsche", "Peugeot"};
    string[] actual = new Test.Enums.Type();      

   //assert
    Assert.Equal(expected, actual);
}

How to correctly get enum values into an array to be able to compare them? I will be grateful for your help.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Goffer
  • 370
  • 1
  • 3
  • 14
  • 2
    `string[] actual = Enum.GetNames();` when comparing collections, use `SequenceEqual()`: `Assert.IsTrue(actual.SequenceEqual(expected));` – Dmitry Bychenko Jun 09 '22 at 08:10
  • 1
    See Microsoft Docs: https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames?view=net-6.0 – Pablo Caballero Jun 09 '22 at 08:14
  • What is the actual use case? Is there some reason the name of the enum value must match some string? Or do you need to convert strings to enum values? Or convert enum values to specific strings? – JonasH Jun 09 '22 at 08:24

2 Answers2

4

Have a look at Enum.GetNames() which returns a string array containing the enum names.

Gabriel
  • 226
  • 2
  • 6
3

Something like this:

using System.Linq;

...

[Fact]
public void Test()
{
    string[] expected = {"Audi", "Porsche", "Peugeot"};
    // Enum names
    string[] actual = Enums.GetNames<Test.Enums.Type>();      

    // Assert: note the when comparing collections / enumerations
    // we should use SequenceEqual 
    Assert.True(expected.SequenceEqual(actual));
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215