Mocco
Mocco

Reputation: 1223

variables of enum are always initialized?

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?

Upvotes: 3

Views: 5181

Answers (6)

xanatos
xanatos

Reputation: 111870

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500735

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.

Upvotes: 7

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46405

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 :

Upvotes: 0

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60694

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.

Upvotes: 2

JoDG
JoDG

Reputation: 1356

You can consider making it nullable

Upvotes: 2

Zebi
Zebi

Reputation: 8882

No way, unless you use Nullable<SomeEnum>.

Upvotes: 3

Related Questions