5YrsLaterDBA
5YrsLaterDBA

Reputation: 34760

C#, Can I move dictionary initial code out from the constructor?

Here is my code right now. But I would like to move those "Add" out from the constructor. Can we initialize Dictionary when we new it? or you have another better idea. Basically I want to define few characters which are used in many places.

public class User
    {
        public enum actionEnum
        {
            In,
            Out,
            Fail
        }

        public static Dictionary<actionEnum, String> loginAction = new Dictionary<actionEnum, string>();

        public User()
        {
            loginAction.Add(actionEnum.In, "I");
            loginAction.Add(actionEnum.Out, "O");
            loginAction.Add(actionEnum.Fail, "F");


        }
 .....
}

Upvotes: 4

Views: 206

Answers (1)

SLaks
SLaks

Reputation: 887453

You can use C# 3's collection initializer syntax:

public static Dictionary<actionEnum, String> loginAction = new Dictionary<actionEnum, string> {
    { actionEnum.In,   "I" }, 
    { actionEnum.Out,  "O" }, 
    { actionEnum.Fail, "F" }
};

Note, by the way, that the dictionary is mutable; any code can add or remove values.

Upvotes: 16

Related Questions