Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explicitly initialize array of enums [C#]

Tags:

arrays

c#

enums

Why does this return an error?

public class Class1
{
    public enum MyEnum
    {
        First,
        Second,
        Third
    }

    public MyEnum[] myEnum;

    public Class1()
    {
        myEnum = 
        {
            MyEnum.First,
            MyEnum.First,
            MyEnum.First
        };
    }
}

Although this does not:

public class Class1
{
    enum MyEnum
    {
        First,
        Second,
        Third
    }

    public MyEnum[] myEnum = 
    {
        MyEnum.First,
        MyEnum.First,
        MyEnum.First
    };

    public Class1()
    {

    }
}

I would like to to it the first way so I can separate the initialization to the constructor. How is this done properly?

like image 677
Ryan R Avatar asked Dec 06 '22 21:12

Ryan R


2 Answers

Use the following syntax:

    public Class1()
    {
        myEnum = new MyEnum[]
        {
            MyEnum.First,
            MyEnum.First,
            MyEnum.First
        };
    }
like image 124
GvS Avatar answered Dec 22 '22 15:12

GvS


The short notation can only be used when the field is declared.

Otherwise, the longer notation must be used:

myEnum = new MyEnum[] { MyEnum.First };

Read more about Array initializers here: http://msdn.microsoft.com/en-us/library/aa664573(v=vs.71).aspx

like image 25
lysergic-acid Avatar answered Dec 22 '22 16:12

lysergic-acid