DEV Community

Kelly Brown
Kelly Brown

Posted on

5 1

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay