How to Set Enum to Null

How to set enum to null

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;

Can an enum be null in C#

HttpStatusCodes Enum

In your particular question about HttpStatusCodes.

What is actually happening is that the "code reader friendly" enum such as StatusCodes.400NotFound is just a representation of an integer value of 400. You can just manually use an integer value as the argument if you like, but then someone else reading your code may not understand the HTTP status code.

For example, if I just wrote in my code the status code422, is it easy to read / understand? Probably not a good idea. Someone reading your code will have a better chance if you use StatusCode.422UnprocessableEntity.

What are the valid HTTP status codes?

If you are sending back an HTTP response, you can designate any of the integer values listed here... https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Unassigned or default behavior(s)?

Without knowing what method or what server you are using, your question about "what happens if it is unassigned". The usual answer is that the server will respond with a 200 (OK) status code as default.

Using non-standard response codes

It really depends on what you are doing, but using response code values that are not part of the standard (ex. -999) may (or may not) error, but you should avoid that as it is not a supported standard.

Nullable Enum

For HttpStatusCodes in all cases (I have ever experienced) you cannot assign a null value to the HttpResponse as the property type is integer.

Note that what I am saying is specific to assigning a status code value to a HttpResponse object. You can read the other answers about the generic question of nullable enums.

How to add and use null value in Enum?

The underlining values of an enum are int which can't be assigned to null.

If you still want to do so:

  1. Add Null as an option to the enum:

    public enum OTA_HotelInvCountNotifRQTarget
    {
    Null,
    Test,
    Production
    }
  2. Have your target a Nullable type:

    Nullable<OTA_HotelInvCountNotifRQTarget> t = null;

    //Or in a cleaner way:
    OTA_HotelInvCountNotifRQTarget? t = null;

    //And in your class:
    public class YourType
    {
    public OTA_HotelInvCountNotifRQTarget? Target { get; set; }
    }

Why does Java allow null value to be assigned to an Enum?

Firstly null means non-existence of an instance. Providing a default constant like DEFAULT or NONE, will change that meaning. Secondly, why would you need something default to represent what seems to be non-existent? That is the purpose of null. Basically, you would have to initialize and store an extra object, which shouldn't even exist whatsoever.

BTW, it's not a language choice. It's completely on you how you implement your enum. You can provide another constant like DEFAULT, or UNKNOWN in your enum, and avoid the assignment of null to the reference in your code. This is famously known as Null Object Pattern. But saying that the null assignment should itself be compiler error, then I would say, since an Enum is anyways compiled to a Class, so it would be perfectly valid to use null to represent non-existence of an instance.

One pitfall of allowing null though is with the usage of enum in switch-case. The below code will throw NPE, even with a default case:

public class Demo {
enum Color {
WHITE, BLACK;
}

public static void main(String[] args) {
Color color = null;

switch (color) { // NPE here
case WHITE: break;
case BLACK: break;
default: break; // null value does not fall into the default
}
}
}

Java does not allow a case null: either, producing the following compile error:

an enum switch case label must be the unqualified name of an enumeration constant

How to include NULL into ENUM on select?

Change the ENUM so that '' is the default and have it mean 'not specified'.

That is:

ENUM ('', 'France','Belgique','Suisse') NOT NULL DEFAULT '';

Then this works:

in ('France','Suisse', '')

(I like to have the first item in the declaration be the default.)

Convert null to Enum.NULL

What you should do is use something else than NULL and parse that case differently:

public enum Type {
CSV, EXCEL, PDF, URL, NONE;
public static Type from(String text) {
if (text == null) {
return NONE;
} else {
return valueOf(text.toUpperCase());
}
}
}

Or better yet, use optionals:

public enum Type {
CSV, EXCEL, PDF, URL; // Note the absence of NULL/NONE/WHATEVER
public static Optional<Type> from(String text) {
return Optional.ofNullable(text)
.map(String::toUpperCase)
.map(Type::valueOf);
}
}

Passing NULL to enum type input parameter - C++

Enums underlying type is ussually int, they are not pointers so they can not be null.

You could either use pointers to your enum, or add a NULL option to your enum. Here is the latter:

enum myEnum{NULL, e1, e2};
enum myEnum2{NULL, e3, e4};

Then call it with the enum's NULL literals.

myFunc(myEnum::NULL, myEnum2::NULL);

Set null value to the array of enums C#

Enums are value types, so null is not a valid value for them.

Here's two solutions to this problem:

  1. add a new enum value:

    public enum Figure { Empty, X, O }

You can now use Figure.Empty instead of null.


  1. Use a nullable type:

    private Figure?[,] board = new Figure[boardSize, boardSize];

The little ? after Figure allows you to use null.

Check enum null when it is not nullable and do not have any null options

Note: the answers below use DataContracts since you've indicated in your question, but similar solutions exist for Json.Net serialization.

You can use [DataMember(EmitDefaultValue = false)] to ignore cases where Gender is not specified at all. In this case, the value that's returned will be whatever enum member is assigned a value of 0 (note that if no member has that value, you'll still get a value of 0, which could be useful for you).

[DataContract]
class Person
{
[DataMember]
public string Name { get; set; }

[DataMember(EmitDefaultValue = false)]
public Gender Gender { get; set; }
}

void Main()
{
var json = "{\"Name\": \"XXX\"}";
var ser = new DataContractJsonSerializer(typeof(Person));
var obj = ser.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
obj.Dump(); // Person { Name = "XXX", Gender = Male }
}

To handle cases where an empty string is provided instead of a valid value or no value at all, you can use this hacky little trick:

[DataContract]
class Person
{
[DataMember]
public string Name { get; set; }

[IgnoreDataMember]
public Gender Gender
{
get
{
if (GenderValue.GetType() == typeof(string))
{
Enum.TryParse((string)GenderValue, out Gender result);
return result;
}
return (Gender)Convert.ToInt32(GenderValue);
}
set
{
GenderValue = value;
}
}

[DataMember(Name = "Gender", EmitDefaultValue = false)]
private object GenderValue { get; set; }
}

void Main()
{
var json = "{\"Name\": \"XXX\", \"Gender\": \"\"}";
var ser = new DataContractJsonSerializer(typeof(Person));
var obj = ser.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
obj.Dump(); // Person { Name = "XXX", Gender = Male }
}

However, this is somewhat awkward and can be easily abused. I'd recommend caution with this approach. As others have mentioned, we typically want to throw errors whenever invalid values are provided to a function / API. By 'failing fast' you let the user attempting to use the API know that they've constructed a request that's likely to produce unexpected results at some point.



Related Topics



Leave a reply



Submit