Lex Webb
Lex Webb

Reputation: 2852

Enum type as parameter in constructor

I am making a file dialog an need to be able to pass a file type mask as part of the constructor. If possible, i would like to store these masks as Enums. Here's an example below:

public enum ImageFileMask {
    Bmp,
    Dds,
    Dib,
    Hdr,
    Jpg,
    Pfm,
    Png,
    Ppm,
    Tga
}

I then check when i chose a file, if it belongs to the file mask using the following line:

if (Enum.IsDefined(ImageFileMask.GetType(), extension))

(extension being the file extension of the chosen file).

This all worked well and good, until i decided that my file dialog will need to accept different file types at different times. I was hoping that i could pass any enum type through the constructor to be stored an evaluated during the file dialog.

The issue is, is that i cannot find a way to get the enum type to be accepted as a parameter in my constructor.

new FileDialogMenu(ImageFileMask);

I always get the following error:

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

I have tried changing the constructor to take a Type, but this has not worked. Is what i am trying even possible? Or do i need to take a different approach to storing the mask.

Upvotes: 3

Views: 926

Answers (3)

C.Evenhuis
C.Evenhuis

Reputation: 26446

You could change the enum to contain all possible types, and make it a [Flags] enum:

[Flags]
public enum ImageFileMask {
    ....

Then your constructor could haven an ImageFileMask allowedImages parameter:

var x = new FileDialogMenu(ImageFileMask.Bmp | ImageFileMask.Jpg);

Once you have a file, you could perform a bitwise comparison:

ImageFileMask extension = ...
if ((allowedImages & extension) == extension)
{
    // the extension is allowed
}

Of course if the enum would grow too large, you could also consider simply supplying a List<string> instead.

Upvotes: 0

Alessandro D&#39;Andria
Alessandro D&#39;Andria

Reputation: 8868

If i understand your question, you want to pass the type of the enum to the constructor of your class, something like this:

class FileDialogMenu
{
    readonly Type enumType;

    public FileDialogMenu(Type enumType)
    {
        this.enumType = enumType;
    }
}

If so you have no problem at doing this:

new FileDialogMenu(typeof(ImageFileMask));

And the you can do (inside your FileDialogMenu class):

if (Enum.IsDefined(enumType, extension))

Well at least that is what i've understood.

Upvotes: 3

algorowara
algorowara

Reputation: 1720

To expand on Daniel's comment, you'll want to declare something like

FileDialogMenu<E> where E : BaseEnum

Where BaseEnum is the parent class of all the appropriate ImageFileMask and related enums.

This link may help you.

Upvotes: 0

Related Questions