Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create constructor for Enum?

Tags:

c#

.net

I have written below code and it's compiling successfully.

class Program
{
        enum Fruits
        {
            Apple,
            Mango,
            Banana
        }

        static void Main(string[] args)
        {
            Fruits f = new Fruits();
        }
}

Despite of Fruits being an enum, compiler and interpreter are allowing me to write this. Does this mean I can create a constructor for an enum? if yes then how?

like image 788
yogi Avatar asked Aug 05 '15 14:08

yogi


2 Answers

No, you can't.

new Fruits() will return the default value (the value corresponding to 0 in the underlying type of the enum), it's the same as default(Fruits) (or Fruits.Apple in your case).

Remeber that enums are only wrappers around a primitive type (int by default). You can pretty much compare new Fruits() to new int().

Usually you don't use the new Fruits()/new int() syntax as it's more common to just write 0 or default(T), but you may want to use it in generic code. As an example:

public T NewInstance<T>()
    where T : new()
{
    return new T();
}

You are allowed to call NewInstance<Fruits>(), which will return Fruits.Apple.

like image 164
Lucas Trzesniewski Avatar answered Sep 19 '22 19:09

Lucas Trzesniewski


C# Spec:

An enum type is a distinct value type with a set of named constants.

As for the default value (as explained in the other answer):

The default value of any enum type is the integral value zero converted to the enum type. In cases where variables are automatically initialized to a default value, this is the value given to variables of enum types. In order for the default value of an enum type to be easily available, the literal 0 implicitly converts to any enum type.

Move the default constant to be the first in your enum.

like image 24
Ofiris Avatar answered Sep 19 '22 19:09

Ofiris