Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize dictionary without values in C#

Tags:

c#

dictionary

I would like to create dictionary with keys only. For example:

Dictionary <string, double> SmplDict= new Dictionary<string, double>();
SmplDict.Add("KeyOne");
SmplDict.Add("KeyTwo");

Of course, I can initialize with some predefined values, but this values will be overwritten, so I want only keys declared for now. I tried

SmpDict.Add("KeyOne", null)

but it did not work.

like image 467
user1700890 Avatar asked Jun 21 '26 07:06

user1700890


1 Answers

You can't put null value where double value is expected, as it is not a reference-type but a value-type:

Dictionary <string, double>

Instead, put 0:

SmpDict.Add("KeyOne", 0)

On the other hand, if you want to keep put nulls, mark your double value as nullable:

Dictionary <string, double?>
like image 194
Yair Nevet Avatar answered Jun 23 '26 20:06

Yair Nevet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!