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?
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
.
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.
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