Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flags enum in .NET

I am trying to use a set of conditional statements that will set up an enumeration attributed with [Flags]. However, the compiler complains that 'm' is unassigned. How can I rewrite the following to achieve my intended functionality?

Media m;
if (filterOptions.ShowAudioFiles)
    m = m | Media.Audio;
if (filterOptions.ShowDocumentFiles)
    m = m | Media.Document;
if (filterOptions.ShowImageFiles)
    m = m | Media.Image;
if (filterOptions.ShowVideoFiles)
    m = m | Media.Video;
like image 516
deckerdev Avatar asked Dec 06 '22 06:12

deckerdev


2 Answers

You need to initialize m. Create a "None" flag that has value 0 then:

Media m = Media.None;

Then the rest of your code.

like image 67
i_am_jorf Avatar answered Dec 23 '22 08:12

i_am_jorf


You could also write:

Media m = default(Media)

Useful in cases where you don't know the enum, class, or whether it's a value/reference type.

like image 20
lightw8 Avatar answered Dec 23 '22 06:12

lightw8