开发者

variables of enum are always initialized?

开发者 https://www.devze.com 2023-02-19 18:17 出处:网络
I开发者_运维知识库 would need to have an enum type variable that is not automatically initialized to value of the first element.

I开发者_运维知识库 would need to have an enum type variable that is not automatically initialized to value of the first element. Is there any way how to do that?


Enum variables aren't always initialized to the first value of the enum.

For instance / static variables, they're initialized to the "0" value of the enum - which may not be a named value, e.g.

enum Color
{
    Red = 1,
    Blue = 2,
    Green = 3
}

Color c; // This will be 0

Local variables aren't initialized automatically - they have to be definitely assigned before the first point at which they can be read, just like any other variable.

It's not really clear what you're trying to achieve - if you could give more details of the context, that would help a lot. Using a nullable value type might be what you want, or you may just want to force initialization within a constructor, for example.


Technically the enum is initialized with 0, not with the first value:

enum Test {
    Second = 1,
    Third = 2
}

Test test;

void Main()
{
    Console.WriteLine("{0}", (int)test);
}

// Result: 0

From MSDN: The default value of an enum E is the value produced by the expression (E)0. http://msdn.microsoft.com/en-us/library/sbbt4032(v=vs.80).aspx


No way, unless you use Nullable<SomeEnum>.


You can consider making it nullable


An enum has an underlying data type of int (by default), and just like an int wi always be initialized, so will the enum.

Your best bet is to add the value Uninitialized as the first entry in the enum.

So for example

public enum MyEnum{ Uninitialized, EnumValue1, EnumValue2, ... };

Then create a instance of it

MyEnum enumInstance;

Now it will still be initialized to the first element in the enum, but you also know that it means you have not initialized it yet.


The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list.

If you wish to represent an unknown value in the enum, you can do it by adding an element Unknown with value 0.
You could declare the field as Nullable< MyNullableEnum >

A helpful link :

  • Should enums have uninitialized values.. ?
0

精彩评论

暂无评论...
验证码 换一张
取 消