Less Magic, Please

thebuzzsaw

Kelly Brown

Posted on December 12, 2020

Less Magic, Please

I haven't posted in a while. I need to fix that. I have a lot of topics I wish to discuss in the near future. For now, here's a quick thought.

C# delegates are great, aren't they?

public string DoTheThing(Func<int, string> handler)
{
    return handler(_data);
}
Enter fullscreen mode Exit fullscreen mode

See how I invoked that delegate? I simply treated it like a method: handler(_data). The issue is that delegates are objects, not methods. I've noticed in my own code that I've taken to writing this instead.

return handler.Invoke(_data);
Enter fullscreen mode Exit fullscreen mode

I never consciously decided to invoke my delegates this way. It sort of just happened. Reflecting on this, I realized that being able to call delegates directly as if they are methods kinda hurts readability. I want my code to be just a bit more explicit. Let's look at another example.

if (flag == true)
Enter fullscreen mode Exit fullscreen mode

Huh? What's going on here? Why bother with the == true part? Let's simplify that.

if (flag)
Enter fullscreen mode Exit fullscreen mode

That's better. Except... C# is angry now.

Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

Ooooooh. I get it. The == true part is a sneaky workaround to the fact that flag is a bool? or Nullable<bool>. In that case, I have a preferred way to handle this.

if (flag.GetValueOrDefault())
Enter fullscreen mode Exit fullscreen mode

See, I don't like obscuring the fact that flag is a Nullable<bool>. I don't want to pretend that it's a flavored bool. The fact is Nullable<T> is its own type with its own rules. The code above makes it abundantly clear to any reader that we are dealing with a bool? and not a bool.

Agree or disagree. I like comments and discussion.

💖 💪 🙅 🚩
thebuzzsaw
Kelly Brown

Posted on December 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related