Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is default value of `KeyValuePair<string, int>`? [duplicate]

Tags:

c#

linq

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>> 
like image 739
Nitin S Avatar asked Jan 28 '14 11:01

Nitin S


People also ask

What is the default value of KeyValuePair?

default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .

What is KeyValuePair C#?

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.

Is KeyValuePair immutable?

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.

How do I change key value pairs?

You can't modify it, you can replace it with a new one.


Video Answer


1 Answers

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.

like image 63
Jon Avatar answered Sep 23 '22 03:09

Jon