Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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");


        }
 .....
}
like image 872
5YrsLaterDBA Avatar asked Dec 06 '22 02:12

5YrsLaterDBA


1 Answers

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.

like image 150
SLaks Avatar answered Feb 01 '23 08:02

SLaks