Search code examples
c#winformsenum-flags

Building a list of enum flags


I have this method that accepts multiple JobSetting flags

private void ProcessTheData(string[] dataFiles, PictureBox sender, JobSetting? jobSetting)

The Flags enum is this

[Flags]
enum JobSetting
{
    ForcePrint = 1,
    ForceProof = 2,
    UseDefault = 4,
    SkipImposition = 8,
    HighPriority = 16,
    SetDP = 32
}

I have a event handler that looks at a CheckboxList and I build a list of flags based on the options that are checked.

JobSetting js;
if (((Control)sender).Name.ToLower().Contains("proof"))
{
    if (chkbxList_Proof.CheckedItems.Contains("Skip Imposition") && chkbxList_Proof.CheckedItems.Contains("High Priority") && chkbxList_Proof.CheckedItems.Contains("_SetDP"))
    {
        js = (JobSetting.ForceProof | JobSetting.SkipImposition | JobSetting.HighPriority | JobSetting.SetDP);
    }
    else if (chkbxList_Proof.CheckedItems.Contains("Skip Imposition") && chkbxList_Proof.CheckedItems.Contains("High Priority"))
    {
        js = (JobSetting.ForceProof | JobSetting.SkipImposition | JobSetting.HighPriority);
    }
    else if (chkbxList_Proof.CheckedItems.Contains("Skip Imposition"))
    {
        js = (JobSetting.ForceProof | JobSetting.SkipImposition);
    }
    else if (chkbxList_Proof.CheckedItems.Contains("High Priority"))
    {
        js = (JobSetting.ForceProof | JobSetting.HighPriority);
    }
    else if (chkbxList_Proof.CheckedItems.Contains("_SetDP"))
    {
        js = (JobSetting.ForceProof | JobSetting.SetDP);
    }
    else
    {
        js = JobSetting.ForceProof;
    }
}

It all works... but I feel like that has to be least effective way to build my list of flags.

I would like to build it in this fashion, or whatever correct way already exists to do it.

JobSeetings js = JobSetting.ForceProof;
if(chkbxList_Proof.CheckedItems.Contains("Skip Imposition"))
{
    js.add(JobSetting.SkipImposition)
}
if(chkbxList_Proof.CheckedItems.Contains("High Priority"))
{
    js.add(JobSetting.HighPriority)
}

Solution

  • You could just combine the flags with bitwise OR based on the items that are checked.

    JobSetting js = JobSetting.ForceProof;
    if (chkbxList_Proof.CheckedItems.Contains("Skip Imposition"))
    {
       js |= JobSetting.SkipImposition;
    }
    if (chkbxList_Proof.CheckedItems.Contains("High Priority"))
    {
       js |= JobSetting.HighPriority;
    }
    //etc, etc...
    

    If "Skip Imposition" and "High Priority" are checked, then js will be equal to JobSetting.ForceProof | JobSetting.SkipImposition | JobSetting.HighPriority.