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