Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set an Enumerated Property in a class to All available enums?

Tags:

c#

enums

First things off, I had no idea what to title this question - I'm even confused how to state it.

Now for the question. Let's take the System.IO.FileSystemWatcher class where you set it's NotifyFilter property:

            this.FileSystemWatcher1.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.FileName 
            | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security 
            | NotifyFilters.Size;

That's quite a bit of code to set a single property. Inspecting NotifyFilter, it is an enumeration. Is there a 'lazy' or 'shortcut' way to set all these properties at once? I know it's not necessarily needed, but my curiosity is piqued.

this.FileSystemWatcher1.NotifyFilter = <NotifyFilters.All> ?

like image 961
Eon Avatar asked Jul 20 '14 20:07

Eon


1 Answers

You could always do something like this,

NotifyFilter ret = 0;
foreach(NotifyFilter v in Enum.GetValues(typeof(NotifyFilter)))
{
    ret |= v;   
}

I don't know of a better way, unfortunately. But you could always throw that in a generic utility method.

private static T GetAll<T>() where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
       throw new NotSupportedException(); // You'd want something better here, of course.
    }

    long ret = 0; // you could determine the type with reflection, but it might be easier just to use multiple methods, depending on how often you tend to use it.
    foreach(long v in Enum.GetValues(typeof(T)))
    {
        ret |= v;
    }

    return (T)ret;
}
like image 65
Matthew Haugen Avatar answered Nov 07 '22 02:11

Matthew Haugen