Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent enum constructors

Tags:

c#

enums

I was surprised, but enums can be created with constructor in C#. For example, I have the enum:

public enum Color
{
    White = 1,
    Red = 2
}

Then it could be created like this:

var color = new Color();

And the value will be 0, which is actually not valid enum value.

So, can we prohibit enum constructors somehow? Any other ideas how to avoid this?

Thanks.

like image 653
Oleg Dudnyk Avatar asked Dec 13 '17 09:12

Oleg Dudnyk


2 Answers

So, can we prohibit enum constructors somehow?

No. The problem is not strictly related to the constructor itself: (Color)0 is valid too, since the underlying type can have the value 0.

Any other ideas how to avoid this?

No, this is basically a broader problem. The only way you can prevent this is by checking your input values on validness.

You should always have a 0 enum value according to Code Analysis.

like image 159
Patrick Hofman Avatar answered Sep 19 '22 12:09

Patrick Hofman


public enum Color is actually the shortened form of the full declaration of an enum, which would be public enum Color : int.

An enum always has an underlying base type, and is technically simply a variable of that type. By default, this type is 32-bit integer, meaning any 32-bit integer can be assigned to such an enum.

The actual enum definitions are merely named members of that type for easy use in programming, allowing you to change or even completely ignore the underlying values without any need to change the code.

But internally, all enums of your type Color (terrible name, by the way) are just Int32 values, and as Anders Forsgren pointed out, like any other Int32 value, they will default to 0 in arrays and any kind of global variables. This is also the reason why the official guidelines recommend always putting a 0 definition in your enum.

like image 29
Nyerguds Avatar answered Sep 21 '22 12:09

Nyerguds