What is default value of KeyValuePair<string, int>
?
e.g. I am running a LINQ query and returning FirstOrDefault()
value from it
KeyValuePair<string, int> mapping = (from p in lstMappings where p.Key.Equals(dc.ColumnName, StringComparison.InvariantCultureIgnoreCase) select p).FirstOrDefault(); if (mapping != null) { }
how to check if mapping
object is null/blank
(I am getting compile time error in above code Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<string,int>' and '<null>'
)
PS: lstMappings
is of type
List<KeyValuePair<string, int>>
default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .
The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.
KeyValuePair is immutable - it's also a value type, so changing the value of the Value property after creating a copy wouldn't help anyway.
You can't modify it, you can replace it with a new one.
The default value of any type T is default(T)
, so for 100% theoretical accuracy you would write
if (!mapping.Equals(default(KeyValuePair<string, int>))) { // ... }
Since KeyValuePair
is a struct
(i.e. a value type) you cannot compare it to null
. Irrespective of that, comparing values with ==
is wrong as a default approach because if used on reference types it normally checks for reference equality.
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