Skip to content

(string[])Request.Headers["NonExistentHeader"] is null while (IEnumerable<string>)Request.Headers["NonExistentHeader"] is not #44509

@hrumhurum

Description

@hrumhurum

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Consider the following code:

string value = string.Join("\n", Request.Headers["NonExistentHeader"]);

It causes the following exception in runtime at method string.Join(string separator, string[] value):

ArgumentNullException: Value cannot be null. (Parameter 'value')

For a very strange reason, the implicit cast of an empty StringValues struct to string[] type returns null:

string[] arr = default(StringValues);
Console.WriteLine("string[] is null: {0}", arr is null);  // prints 'string[] is null: True' message

While a similar cast to IEnumerable returns an expected non-null value:

var seq = (IEnumerable<string>)default(StringValues);
Console.WriteLine("IEnumerable<string> is null: {0}", seq is null);  // prints 'IEnumerable<string> is null: False' message

When C# compiler compiles string.Join("\n", Request.Headers["NonExistentHeader"]) expression, it selects string.Join(string separator, string[] value) overload and this makes the expression to crash at runtime. While the project has nullable checks enabled, C# compiler is not able to catch that null reference error at compile time.

It looks like a bug because structs are never expected to be null and thus their cast operators should avoid producing null values as well, unless there is a very good reason for that.

The following approach allows to workaround the issue:

string value = string.Join("\n", (IEnumerable<string>)Request.Headers["NonExistentHeader"]);

It would be nice to have a consistent behavior here (non-null string[] is expected and preferred). But even if there is a null then C# compiler should be able to catch it at compile time.

Expected Behavior

(string[])default(StringValues) aways returns a non-null value.

Steps To Reproduce

string value = string.Join("\n", Request.Headers["NonExistentHeader"]);

Exceptions (if any)

ArgumentNullException: Value cannot be null. (Parameter 'value')
at string.Join(string separator, string[] value)

.NET Version

6.0.401

Anything else?

Server: Kestrel

Metadata

Metadata

Assignees

Labels

area-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsuntriaged

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions