Quite often in my code I need to compare a variable to several values :
if ( type == BillType.Bill || type == BillType.Payment || type == BillType.Receipt ) { // Do stuff }
I keep on thinking I can do :
if ( type in ( BillType.Bill, BillType.Payment, BillType.Receipt ) ) { // Do stuff }
But of course thats SQL that allows this.
Is there a tidier way in C#?
Use scatterplots to compare two continuous variables. Use scatterplot matrices to compare several pairs of continuous variables. Use side-by-side box plots to compare one continuous and one categorical variable. Use variability charts to compare one continuous Y variable to one or more categorical X variables.
To have a comparison of three (or more) variables done correctly, one should use the following expression: if (a == b && b == c) .... In this case, a == b will return true, b == c will return true and the result of the logical operation AND will also be true.
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value.
You could do with with .Contains
like this:
if (new[] { BillType.Receipt, BillType.Bill, BillType.Payment}.Contains(type)) {}
Or, create your own extension method that does it with a more readable syntax
public static class MyExtensions { public static bool IsIn<T>(this T @this, params T[] possibles) { return possibles.Contains(@this); } }
Then call it by:
if (type.IsIn(BillType.Receipt, BillType.Bill, BillType.Payment)) {}
There's also the switch statement
switch(type) { case BillType.Bill: case BillType.Payment: case BillType.Receipt: // Do stuff break; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With