deckerdev
deckerdev

Reputation: 2792

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;

Upvotes: 4

Views: 1865

Answers (7)

Pascal Senn
Pascal Senn

Reputation: 1912

The Problem with the accepted approach is, that you need to have a default element. In case you do not want to have the None element, then you can use nullability.

Media? m = null;
if (filterOptions.ShowAudioFiles)
    m ??= Media.Audio;
    m = m | Media.Audio;
if (filterOptions.ShowDocumentFiles)
    m ??= Media.Document;
    m = m | Media.Document;
if (filterOptions.ShowImageFiles)
    m ??= Media.Image;
    m = m | Media.Image;
if (filterOptions.ShowVideoFiles)
    m ??= Media.Video;
    m = m | Media.Video;

// in case you require a value for m you can do:
if( m is null ) { throw ... }

Upvotes: 0

Matthew Whited
Matthew Whited

Reputation: 22433

You don't really need to create a Media.None. You can cast any value to the Flag enum even if it doesn't equal to a value of the flags.

Media m = (Media)0;

if (filterOptions.ShowAudioFiles)     m |= Media.Audio; 

if (filterOptions.ShowDocumentFiles)  m |= Media.Document; 

if (filterOptions.ShowImageFiles)     m |= Media.Image; 

if (filterOptions.ShowVideoFiles)     m |= Media.Video;

Upvotes: -5

lightw8
lightw8

Reputation: 3282

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.

Upvotes: 2

hmcclungiii
hmcclungiii

Reputation: 1805

In addition to the above answers, besides the fact that this code seems pretty redundant, I'd like to suggest that you use a Select Case instead of all those ugly If's.

Upvotes: 0

n8wrl
n8wrl

Reputation: 19765

Do you have a 'default' like filterOptions.ShowNone? If so, start off with m set to that. The compiler is complaining becuase at the end of all the if's, m might not be set to anything.

Upvotes: 1

i_am_jorf
i_am_jorf

Reputation: 54600

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

Media m = Media.None;

Then the rest of your code.

Upvotes: 18

EricSchaefer
EricSchaefer

Reputation: 26330

If none of the conditions are true m will be undefined. Set it to an initial value.

Upvotes: 1

Related Questions