Listing flags in .NET.

I am trying to use a set of conditional statements that will create an enumeration related to [Flags]. However, the compiler complains that "m" is not assigned. 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;
+3
source share
6 answers

You need to initialize m. Create a No flag that has a value of 0, then:

Media m = Media.None;

Then the rest of your code.

+16
source

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

+1
source

"default", filterOptions.ShowNone? , m, . , if, m .

+1

:

Media m = default(Media)

, enum, class / .

+1
source

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

0
source

You do not need to create Media.None. You can pass any value to the Flag enumeration, even if it is not equal to the 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;
-3
source

Source: https://habr.com/ru/post/1706244/


All Articles