I have an object of the type IEnumerable<KeyValuePair<T,U>> keyValueList
, I am using
var getResult= keyValueList.SingleOrDefault(); if(getResult==/*default */) { } else { }
How can I check whether getResult
is the default, in case I can't find the correct element?
I can't check whether it is null
or not, because KeyValuePair
is a struct.
The object and string types have a default value of null, representing a null reference that literally is one that does not refer to any object.
Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
KeyValuePair<TKey, TValue> is a structure, therefore a value type and cannot be null. Default value of a struct is stuct populated with default values of it's members. In this example it would be: new KeyValuePair(null, 0)
} 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.
Version 1: The keys and values are stored in 2 separate arrays. The GC.GetTotalMemory method measures the memory usage. Version 2: This version uses a single array of KeyValuePair structs. Again, the GC.GetTotalMemory method is used. Result: The version that uses 1 array of KeyValuePairs uses a few bytes less of memory.
A common use of KeyValuePair is in a loop over a Dictionary. The Dictionary has an enumerator that returns each key and value in a KeyValuePair, one at a time.
Try this:
if (getResult.Equals(new KeyValuePair<T,U>()))
or this:
if (getResult.Equals(default(KeyValuePair<T,U>)))
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