Goral Patel Goral Patel - 4 months ago 28
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 );


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.