Bryan Bryan - 1 year ago 75
C# Question

Error when trying to enumerate enum

I have the following model:

public class FormModel
public Guid {get; set;}
public Sections Sections {get; set}

public enum Sections
Test1= 0,
Test2= 1,
Test3= 2,
Test4= 4,
Test5= 8,
Test6= 16

Im using a service that returns the model with data:

var form = await _formService.GetById(formAnswer.FormId);

Now the Sections-property contains:
Test1 | Test2

Im trying to enumerate this property like this:

var list = new List<string>();
foreach(var item in Enum.GetValues(typeof(form.Sections)))
//Add the form.Sections into the list.

But I get the error:

'form' is a variable but is used like a type

How can I enumerate the Sections-property of my model and add the values to a list?

Answer Source

you have a typo. You used the form instance, instead you wanted the type of the enum. Try:

foreach (var item in Enum.GetValues(typeof(Sections)))
    if (((int)form.Sections & (int)item) != 0)
         // add to list