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?
Use the following syntax:
public Class1()
{
myEnum = new MyEnum[]
{
MyEnum.First,
MyEnum.First,
MyEnum.First
};
}
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
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