Goral Patel Goral Patel - 1 year ago 134
C# Question

How to convert array of string to enum?

How can I convert an array of string to enum?
The following code gives a basic idea about what is expected,

permission.Permissions.Add(Enum.Parse(typeof(PagePermission) ,a );

however, it throws an error like

can not convert object to enum.

is enum.

string pagePermission = "View,Edit";
string[] permissions = pagePermission.Split(',');
permission.Permissions = new List<PagePermission>();
for (int i = 0; i < permissions.Length; i++)
string a = permissions[i];
permission.Permissions.Add(Enum.Parse(typeof(PagePermission) ,a );

Answer Source

Enum.Parse returns an object, you need to cast it to the actual enum type. In your case:

permission.Permissions.Add((PagePermission)Enum.Parse(typeof(PagePermission), a);

Otherwise you'd be adding an object to a list of PagePermission, which causes the error you had.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download