Is there a (well-hidden) generic listing anywhere in the BCL for Enabled / Disabled?

So, I just hate using true / false as method arguments for "enabled" / "disabled". To quote Jeff freely: "I don't like it at the fundamental level."

I have repeatedly found that I define my own enumerations for each new project in different namespaces, for example:

 public enum Clickability { Disabled, Enabled } public enum Editability { Disabled, Enabled } public enum Serializability { Disabled, Enabled } 

Is there a generic listing that I can use for these scenarios?

+6
enums c #
source share
3 answers

The problem is that it actually does not help in real problem cases, when there are several arguments, and it is unclear what the flag controls.

If you follow the rule that you should “avoid double negatives,” then simple single booleans are in order:

 public static void Foo(bool useBaz) public static void Foo(Ability useBaz) 

Then Foo(true) , verses Foo(Ability.Enabled) and Foo(false) , verses Foo(Ability.Disabled) really very obvious to most.

However, when you click on a method, for example:

 public static void Foo( bool useBaz, bool barIsHigh, bool useFlibble, bool ignoreCase) 

then it doesn’t matter if you use the logical or general enumerations that they still look on this site:

 Foo(false,true,false,false); Foo(Ability.Enabled,Ability.Enabled,Ability.Disabled,Ability.Enabled); 

Nothing happens.

Using specific listings for the case in question:

 enum BarOption { Off, On } enum BazConsidered { Low, High } enum FlibbleOption { Off, On } // for case sensitivity use System.StringComparison 

then you get

 Foo(Bar.On, BazConsidered.Low, FlibbleOption.On, StringComparison.IgnoreCase ); 

or, if all are simple Boolean states and are likely to remain so, then a flag enumeration is best.

 [Flags] enum FooOptions { None = 0, UseBaz = 1, BazConsideredHigh = 2, UseFlibble = 4, } 

Then you will have:

 Foo(FooOptions.UseBar | FooOptions.UseFlibble, StringComparison.IgnoreCase); 

The appropriate choice of “active” flags so that you specify only what is unusual, then leads to highlighting “unusual” customs.

+7
source share

No, there is no such listing in BCL (as far as I know). But it’s not difficult to take one of those that you repeatedly create and make it more general:

 public enum Ability { Disabled, Enabled } 

Paste it into some class library with similar common material and reuse it in your projects.

0
source share

What is wrong with using bool parameters with meaningful names?

 public void Foo(bool clickabilityEnabled, bool editabilityEnabled) { ... } 

Or, even better, something a little less verbose:

 public void Bar(bool isClickable, bool isEditable, bool isSerializable) { ... } public void Baz(bool canClick, bool canEdit, bool canSerialize) { ... } 

I would find this much more readable than enum parameter loads.

0
source share

All Articles