C# Question

Adding CustomClassObjects to Dictionary as values

I have a task where I need to have two values for one key in Dictionary.
Solution found in web is to make new class with two fields and use it's objects as values.

But how can I assign value to my CustomClassObjects from Dictionary's for loop?
Here is the code:

Dictionary<char, Huffmans> HuffmanDictionary = new Dictionary<char, Huffmans>();
Program.text = File.ReadAllText(Program.sourcetext);
char character;
for (int i = 0; i < Program.text.Length; i++)
{
counter++;
character = Convert.ToChar(Program.text[i]);
if (HuffmanDictionary.ContainsKey(character))
HuffmanDictionary[character].probability++;
else
HuffmanDictionary.Add(character, 1);// here is the problem, obviously program can't assign value directly to class...
}
public class Huffmans
{
public int code = 0;
public double probability = 0;
}


Basically, I need to assign only "probability" values on this step. Should I call constructor for "Huffmans " on each iteration?

Big thanks for any help, Alex

Answer

You need to instantiate your class before adding the value:

HuffmanDictionary.Add(character, 1);

Should be:

HuffmanDictionary.Add(character, new Huffmans{ code = 1 });

Alternatively you can create a constructor for your class:

public class Huffmans
{
    public Huffmans(int _code)
    {
       code = _code;
    }

    public int code = 0;
    public double probability = 0;
}  

then you can do:

 HuffmanDictionary.Add(character, new Huffmans(1));

EDIT: Some more clarification:

HuffmanDictionary.Add(character, 1);

fails because you are passing a type int into the dictionary but it is expecting the type Huffmans. Our dictionary is : Dictionary<char,Huffmans>()

HuffmanDictionary.Add(character, new Huffmans{ code = 1 }); 

works because now we are creating a new object of type Huffmans and we are setting the code value to 1.

Not sure if I understood your comment correctly, but effectively we are doing the same as:

var newHuffmans = new Huffmans{ code = 1 };
HuffmanDictionary.Add(character, newHuffmans);

But rather than writing out all that code and creating a named variable with our class, we skip this and pass it directly into the dictionary.