KeyValuePair<TKey, TValue> is a struct (value type).
The default value for any struct in C# is an instance of that struct where all its fields are set to their default values.
For KeyValuePair<TKey, TValue>, its two main (publicly accessible via properties) fields are Key (of type TKey) and Value (of type TValue).
Therefore, the default value for KeyValuePair<TKey, TValue> is:
Key: default(TKey)
Value: default(TValue)
Examples:
KeyValuePair<string, int>:
default(string) is null.
default(int) is 0.
So, default(KeyValuePair<string, int>) will have Key = null and Value = 0.
KeyValuePair<int, bool>:
default(int) is 0.
default(bool) is false.
So, default(KeyValuePair<int, bool>) will have Key = 0 and Value = false.
KeyValuePair<MyClass, MyStruct> (where MyClass is a custom class and MyStruct is a custom struct):
default(MyClass) is null (since MyClass is a reference type).
default(MyStruct) is an instance of MyStruct with all its fields set to their respective defaults.
So, default(KeyValuePair<MyClass, MyStruct>) will have Key = null and Value = default(MyStruct).
How to get the default value in code:
You can get the default value using either:
csharp
KeyValuePair<TKey, TValue> kvp1 = default;
// or
KeyValuePair<TKey, TValue> kvp2 = new KeyValuePair<TKey, TValue>(); // The parameterless constructor for structs initializes fields to their defaults
Demonstration:
csharp
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
// Example 1: string, int
KeyValuePair<string, int> kvpStringInt = default;
Console.WriteLine($"Default KeyValuePair<string, int>: Key='{(kvpStringInt.Key == null ? "null" : kvpStringInt.Key)}', Value='{kvpStringInt.Value}'");
// Output: Default KeyValuePair<string, int>: Key='null', Value='0'
KeyValuePair<string, int> kvpStringIntNew = new KeyValuePair<string, int>();
Console.WriteLine($"New KeyValuePair<string, int>: Key='{(kvpStringIntNew.Key == null ? "null" : kvpStringIntNew.Key)}', Value='{kvpStringIntNew.Value}'");
// Output: New KeyValuePair<string, int>: Key='null', Value='0'
// Example 2: int, bool
KeyValuePair<int, bool> kvpIntBool = default;
Console.WriteLine($"Default KeyValuePair<int, bool>: Key='{kvpIntBool.Key}', Value='{kvpIntBool.Value}'");
// Output: Default KeyValuePair<int, bool>: Key='0', Value='False'
// Example 3: Custom class, Custom struct
KeyValuePair<MyClass, MyStruct> kvpCustom = default;
Console.WriteLine($"Default KeyValuePair<MyClass, MyStruct>: Key='{(kvpCustom.Key == null ? "null" : "not null")}', Value.MyInt='{kvpCustom.Value.MyInt}', Value.MyBool='{kvpCustom.Value.MyBool}'");
// Output: Default KeyValuePair<MyClass, MyStruct>: Key='null', Value.MyInt='0', Value.MyBool='False'
}
}
public class MyClass { }
public struct MyStruct
{
public int MyInt;
public bool MyBool;
// Note: Custom structs implicitly have a parameterless constructor
// that initializes fields to their defaults.
}