Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The default for KeyValuePair

Tags:

c#

key-value

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.

like image 844
Graviton Avatar asked Oct 29 '09 03:10

Graviton


People also ask

What is the default value of string in C#?

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.

How do you check if a key value pair exists in a dictionary C#?

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.

What is the default value of KeyValuePair<TKey>?

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)

Why can't I compare a KeyValuePair to null?

} 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.

What is the difference between version 1 and version 2 keyvaluepairs?

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.

How do you use KeyValuePair in Python?

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.


1 Answers

Try this:

if (getResult.Equals(new KeyValuePair<T,U>())) 

or this:

if (getResult.Equals(default(KeyValuePair<T,U>))) 
like image 174
Andrew Hare Avatar answered Oct 11 '22 04:10

Andrew Hare