Compiler warning when using const boolean

I came across an unexpected compiler warning using the following code:

private const bool DEFAULT_SETTING = false;
//...
string aString = (DEFAULT_SETTING) ? "1" : "0";

which generates a warning warning CS0429: Unreachable expression code detected.

After I was puzzled, I realized that the compiler is not mistaken, because the value DEFAULT_SETTINGis constant and cannot change. Therefore, part of the ? "1"triple operator cannot be reached . But none of them is completely correct, because I or the future developer may (or need) to change the default value without breaking the code.

Can I use a default setting similar to the above context that does not generate a warning?

Note. You might want to know why I would like to convert falseto "0"... is to save the settings file. When a file is missing, the software automatically generates a new shiny XML file with default settings.

+4
source share
3 answers

Can I use a default setting similar to the above context that does not generate a warning?

Yes.

But first: stop using SHOUTY_SNAKE_CASINGright now. It looks like you're a C programmer. C # uses camelCasing and PascalCasing.

. , . , . Pi - . . , , . .

, , , , -, , , , .

; # , . , Foo Foo.DLL, Bar.EXE, Foo.DLL Foo Foo Bar.EXE. # , Foo Bar.EXE.

" , " readonly:

private static readonly bool DefaultSetting = false;
...
string aString = DefaultSetting ? "1" : "0";
+13

. :

#define DEFAULT_SETTING

:

#if DEFAULT_SETTING
    string aString = "1";
#else
    string aString = "0";
#endif

#define DEFAULT_SETTING aString = "0"; string aString = "1"; .

+2

Use an extension like this:

public static class BooleanExtensions {
   public static string ToOneOrZero(this bool value) {
      return value ? "1" : "0";
   }
}

Using:

var val = DEFAULT_SETTING.ToOneOrZero();

You will not receive a warning, and it is cleaner. I think so.

0
source

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


All Articles