3

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.

0

5 Answers 5

5

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?>
Sign up to request clarification or add additional context in comments.

Comments

4

You have to make it nullable, if you want to put null:

Dictionary <string, double?> SmplDict= new Dictionary<string, double?>();

Now you can add null as value:

SmpDict.Add("KeyOne", null)

Comments

3
Dictionary<string, double?> smplDict = new();
smplDict.Add("KeyOne", default);
smplDict.Add("KeyTwo", default);

I would mention that it might be that you are doing something wrong that this is your need. Maybe you can use some other collection that is more suitable, e.g: HashSet<T>.

Comments

2

If you want your values to be null then choose a type that can be nullable for the Value.Such as double?, object etc...

Comments

1

While a double can't be null there is a Not-a-Number constant:

Dictionary <string, double?> SmplDict= new Dictionary<string, Double.NaN>();

for which you can check..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.