0

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.

Here, PagePermission 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 ); } 
4
  • When asking a question on StackOverflow, please always copy/paste the exact message of the exception. There's a lot that can be deduced from the precise wording of the error message Commented Nov 2, 2016 at 7:24
  • Please add the declaration of PagePermission enum. Commented Nov 2, 2016 at 7:26
  • public enum PagePermission { View = 1, Edit = 2 } Commented Nov 2, 2016 at 7:32
  • Exact message of exception : Can not convert from 'object' to 'PagePermission' enum. Commented Nov 2, 2016 at 7:33

2 Answers 2

7

Use this

IEnumerable<myEnum> items = myArray.Select(a => (myEnum)Enum.Parse(typeof(myEnum), a)); 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

@GoralPatel That's the (PagePermission) bit I added before Enum.Parse(typeof(PagePermission), a). It's used to tell "I know this object is a PagePermission, so consider it as such"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.