0

I have the following model:

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

[Flags]
    public enum Sections
    {
        Test1= 0,
        Test2= 1,
        Test3= 2,
        Test4= 4,
        Test5= 8,
        Test6= 16
    }

I'm using a service that returns the model with data:

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

Now the Sections-property contains: Test1 | Test2

I'm 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?

halfer
  • 18,701
  • 13
  • 79
  • 158
Bryan
  • 2,793
  • 7
  • 28
  • 56

1 Answers1

1

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
    }
}
Nico
  • 3,377
  • 18
  • 26
  • But If I do this, I enumerate the whole enum. Not the Sections-property from my result from the service.. – Bryan Nov 09 '16 at 13:01
  • @Bryan Ah, now I see what you wanted, check the update – Nico Nov 09 '16 at 13:04
  • 1
    Hehe, I tried like your answer before with this: if ((int)form.Sections & (int)item) > 0) { }, but I got a error. Now I see that I forgot a parentheses. Thank you! – Bryan Nov 09 '16 at 13:08
  • 1
    You can also use `if(form.Sections.HasFlag(item))`, to hide the casting and boolean logic. – Oliver Nov 09 '16 at 13:39