views:

334

answers:

3

Is there a simple way to initialize a dictionary that is a property like in .Net 3.5 or do I need to add the elements in the class's constructor?

My aim is to have a static map of codes mapping to string representation.

+1  A: 

If you class is static you can do it in a static constructor? static myclass() { //Do stuff here?! }

if its not do it in your instance constructor?

Petoj
No nifty way like in C3 3.0+?
Shaihi
+4  A: 

Yes, you'll need to initialize your Dictionary at class constructor.

Rubens Farias
+1  A: 

The Collection Initializer syntax is only available for Dictionaries in .NET 3.5 and going forward.

FTA:

This feature (collection initialization) requires the C# 3.0 compiler wich was introduced with Visual Studio 2008 and only works with .NET 3.5 or later. Static initialization only works for arrays in previous versions.

However, you're not limited to adding the elements in your classes constructor. You can add then any time you want, you just can't do it using collection initialization.

Joseph
I saw that, but wanted to see if there was a method I was not familiar with. Thanks.
Shaihi
the requirement is C# 3.0, not .NET 3.5, because it works (with the C# 3.0 compiler) even if targeting .Net 2.0
Lucas