How to set enum to null
Asked Answered
O

9

238

I have an enum

string name;

public enum Color
{
  Red,
  Green,
  Yellow
}

How to set it to NULL on load.

name = "";
Color color = null; //error

Edited: My bad, I didn't explain it properly. But all the answers related to nullable is perfect. My situation is What if, I have get/set for the enum in a class with other elements like name, etc. On page load I initiallize the class and try to default the values to null. Here is the scenario (Code is in C#):

namespace Testing
{
    public enum ValidColors
    {
        Red,
        Green,
        Yellow
    }

    public class EnumTest
    {
        private string name;
        private ValidColors myColor;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public ValidColors MyColor
        {
            get { return myColor; }
            set { myColor = value; }
        }

    }

    public partial class _Default : System.Web.UI.Page
    {       
        protected void Page_Load(object sender, EventArgs e)
        {
            EnumTest oEnumTest = new EnumTest();
            oEnumTest.Name = "";
            oEnumTest.MyColor = null; //???
        }
    }

}

Then using the suggestions below I changed the above code to make it work with get and set methods. I just need to add "?" in EnumTest class during declaration of private enum variable and in get/set method:

public class EnumTest
{
    private string name;
    private ValidColors? myColor; //added "?" here in declaration and in get/set method

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public ValidColors? MyColor
    {
        get { return myColor; }
        set { myColor = value; }
    }

}

Thanks all for the lovely suggestions.

Orlina answered 2/12, 2010 at 16:20 Comment(1)
Possible duplicate of C# Enums: Nullable or 'Unknown' Value?Unarm
A
448

You can either use the "?" operator for a nullable type.

public Color? myColor = null;

Or use the standard practice for enums that cannot be null by having the FIRST value in the enum (aka 0) be the default value. For example in a case of color None.

public Color myColor = Color.None;
Archduke answered 2/12, 2010 at 16:23 Comment(7)
@equiman no need to cast since the type is specified on the left, you are basically duplicating the first part of my answer that is already accepted.Archduke
this answered my question: Can you add '?' to enumname to make it nullable?Platonic
for those who already have the nullable type declared in their class and come here: myColor = (Color?)null;Empoison
@Empoison you don't need to cast the null if its already a declared nullable type of Color just myColor = null is fine.Archduke
I don't know what the issue is then, but for my compiler it did give errors until I did the cast.Empoison
@Empoison Yeah in the latest VS2017 and VS2019 no compiler errors for me. You could have something set in your csproj file that is triggering this. if you could create a standalone project and reproduce the issue using a built-in enum like Color as shown in example above and share it that would be cool to see the issue. Also sharing the compiler error in full including error numbers.Archduke
@RodneyS.Foley Will do once I find some time, I'm using Rider 2019.2 so that might be the difference.Will check in Visual studio as well.Empoison
T
54

If this is C#, it won't work: enums are value types, and can't be null.

The normal options are to add a None member:

public enum Color
{
  None,
  Red,
  Green,
  Yellow
}

Color color = Color.None;

...or to use Nullable:

Color? color = null;
Terriss answered 2/12, 2010 at 16:24 Comment(0)
E
28

Make your variable nullable. Like:

Color? color = null;

or

Nullable<Color> color = null;
Exile answered 2/12, 2010 at 16:23 Comment(0)
C
15

An enum is a "value" type in C# (means the the enum is stored as whatever value it is, not as a reference to a place in memory where the value itself is stored). You can't set value types to null (since null is used for reference types only).

That being said you can use the built in Nullable<T> class which wraps value types such that you can set them to null, check if it HasValue and get its actual Value. (Those are both methods on the Nullable<T> objects.

name = "";
Nullable<Color> color = null; //This will work.

There is also a shortcut you can use:

Color? color = null;

That is the same as Nullable<Color>;

Canberra answered 2/12, 2010 at 16:24 Comment(0)
P
8

Some observations and gotchas when working with Nullable enum as class/method variables, and class properties:


In C# v7.3 (tested on .NET v4.7.2 with VS2019),

this works:

Color? color = null; // works

but this doesn't:

Color? color = condition ? Color.Red : null;

// Error CS8370 
// Feature 'target-typed conditional expression' is not available in C# 7.3.  
// Please use language version 9.0 or greater.

The fix is to type-cast null:

Color? color = condition ? Color.Red : (Color?)null; // works

Furthermore, naming the variable Color, i.e. exactly the same case as the type, works only when the type is non-Nullable:

Color Color = condition ? Color.Red : Color.None; // works fine!

But fails miserably when the type is Nullable:

Color? Color = condition ? Color.Red : (Color?)null;

// Error CS0165 Use of unassigned local variable 'Color'
// Error CS1061 'Color?' does not contain a definition for 'Red' 
// and no accessible extension method 'Red' accepting a first argument of type 'Color?' 
// could be found (are you missing a using directive or an assembly reference?)

The fix is to use the fully-qualified name of the type with the namespace:

Color? Color = condition ? MyEnums.Color.Red : (Color?)null; // works now

But it is best to stick to standard practice of lower-case naming for the variable:

Color? color = condition ? Color.Red : (Color?)null; // works now

A similar problem can be seen for a property at class-level:

class Program {
    Color? Color => Condition ? Color.Red : (Color?)null;
}

// Error CS1061 'Color?' does not contain a definition for 'Red' 
// and no accessible extension method 'Red' accepting a first argument of type 'Color?' 
// could be found (are you missing a using directive or an assembly reference?)

Again, the fix is to fully-qualify the type:

Color? Color => Condition ? MyEnums.Color.Red : (Color?)null; // works now
Paleopsychology answered 7/10, 2021 at 22:20 Comment(2)
Just saved the day!Psittacosis
well explained! solved my problem. Thanks a lot.Prinz
R
3

I'm assuming c++ here. If you're using c#, the answer is probably the same, but the syntax will be a bit different. The enum is a set of int values. It's not an object, so you shouldn't be setting it to null. Setting something to null means you are pointing a pointer to an object to address zero. You can't really do that with an int. What you want to do with an int is to set it to a value you wouldn't normally have it at so that you can tel if it's a good value or not. So, set your colour to -1

Color color = -1;

Or, you can start your enum at 1 and set it to zero. If you set the colour to zero as it is right now, you will be setting it to "red" because red is zero in your enum.

So,

enum Color {
red =1
blue,
green
}
//red is 1, blue is 2, green is 3
Color mycolour = 0;
Romano answered 2/12, 2010 at 16:28 Comment(0)
A
0
Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 
Alterant answered 6/11, 2019 at 14:7 Comment(0)
S
0

would it not be better to explicitly assign value 0 to None constant? Why?

Because default enum value is equal to 0, if You would call default(Color) it would print None.

Because it is at first position, assigning literal value 0 to any other constant would change that behaviour, also changing order of occurrence would change output of default(Color) (https://mcmap.net/q/93143/-what-is-the-default-value-for-enum-variable)

Shana answered 17/12, 2019 at 10:20 Comment(0)
S
-1

It is done so sample like this

public enum Colors
 {
  None,
  Red,
  Green,
  Yellow
   }

  Color colors = Colors.null;
Swink answered 5/5, 2022 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.