Shaihi
Shaihi

Reputation: 3974

Initialize Dictionary in .Net 2.0

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.

Upvotes: 4

Views: 2557

Answers (3)

Peter
Peter

Reputation: 38455

If your class is static you can do it in a static constructor.

static myclass()
{
    //Do stuff here?!
}

If it's not, do it in your instance constructor?

Upvotes: 2

Joseph
Joseph

Reputation: 25513

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.

Upvotes: 1

Rubens Farias
Rubens Farias

Reputation: 57936

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

Upvotes: 4

Related Questions