Check if Key Exists in NameValueCollection

From MSDN:

This property returns null in the following cases:

1) if the specified key is not found;

So you can just:

NameValueCollection collection = ...
string value = collection[key];
if (value == null) // key doesn't exist

2) if the specified key is found and its associated value is null.

collection[key] calls base.Get() then base.FindEntry() which internally uses Hashtable with performance O(1).


This method handles the case when key is within the collection and its associated value is null.

private static bool ContainsKey(this NameValueCollection collection, string key) =>
    collection.Get(key) is not null || collection.AllKeys.Contains(key);

Starting from C# 9 you can use is not null, otherwise use != null