Reputation: 2792
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
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
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
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
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
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
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
Reputation: 26330
If none of the conditions are true m will be undefined. Set it to an initial value.
Upvotes: 1