DEV Community

loading...

Two CSharp idioms

canro91 profile image Cesar Aguirre Updated on ・1 min read

Two useful C# idioms you can find and its alternative solutions.

  • Instead of lots of or’s, use an array. You can find this code when checking preconditions or validating objects.
if (myVar == 2 || myVar == 5 || myVar == 10)
    DoSomeOperation();
Enter fullscreen mode Exit fullscreen mode
var allowedValues = new int[] { 2, 5, 10 };
if (allowedValues.Any(t => myVar == t))
    DoSomeOperations();
Enter fullscreen mode Exit fullscreen mode

If you need to validate a new value, you add it in the array instead of adding a new condition in the if statement.

  • Instead of lots of if to find a value, use an array of Func and pick the first value different from null or a default value. You can find this code when finding a value among multiple choices.
var someKey = FindKey();
if (someKey == null)
    someKey = FindAlternateKey();
if (someKey == null)
    someKey = FindDefaultKey();
Enter fullscreen mode Exit fullscreen mode
var fallback = new List<Func<SomeObject>>
{
    FindKey(),
    FindAlternateKey(),
    FindDefaultKey()
};
var someKey = fallback.FirstOrDefault(t => t != null);
Enter fullscreen mode Exit fullscreen mode

But, you could take advantage of Null coleasing operator (??) if these choice functions return null when a value isn't found.

var someKey = FindKey() ?? FindAlternateKey() ?? FindDefaultKey();
Enter fullscreen mode Exit fullscreen mode

Similarly, if you need to add a new alternative, either you add it in the array or nest it instead of adding the new alternative in the if statement.

I have found these two idioms more readable. But, make sure to follow the conventions in your codebase.

Discussion (3)

pic
Editor guide
Collapse
serinus1 profile image
Serinus1

Granted, they're just examples, but in the examples given the first solution is better. It's immediately obvious what you're doing to any programmer of any skill level from any language, and they take fewer lines.

The "idioms" as you call them can be useful tricks, but they require overhead knowledge. More developers are familiar with "or" and boolean logic than lambdas and linq. I would avoid using these tricks in the examples given. I would look to use these if they reduced, say 50 lines into 5 lines. In that case the overhead knowledge requirement is serving a purpose.

You always should have a reason to be clever and don't just try to be clever for the sake of it. Keep it simple and stupid whenever possible.

Collapse
reidterror profile image
reidterror

For the first one, would the performance take a hit?

Collapse
canro91 profile image
Cesar Aguirre Author

I don't think so (unless you're working with lots of options, in that case you would need another abstraction). It strives for readability: make it work, clean and then fast