Just wondering if an enum
can be null in C#?
Specifically I'm interested in the HttpStatusCode
implementation of enum
in C#.
What will happen if I will not assign a value to a variable of the HttpStatusCode
type? What will happen if I will try to assign a value that is not expected?
From MSDN:
Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type, as shown in the following example. C#
enum Day : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
Since these are only value types, the enum itself cannot be null
.
Of course you can wrap it in a Nullable, which allows value types to behave "nullable", but technically, Nullable<T>
is a generic struct type (non-nullable) and not an enum itself, it's just a wrapper as by definition:
public struct Nullable<T> where T : struct
You might wonder: how can a struct be null
? See this answer for an explanation:
Nullable<bool> b = new Nullable<bool>();
Basically, it's never null
. It a compiler trick to guarantee that the values like e.g.: HasValue
are always available.
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 code
422
, is it easy to read / understand? Probably not a good idea. Someone reading your code will have a better chance if you useStatusCode.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.
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.
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