4

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.

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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?

1 Comment

No nifty way like in C3 3.0+?
1

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.

2 Comments

I saw that, but wanted to see if there was a method I was not familiar with. Thanks.
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

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.