Kelly Brown
Posted on December 12, 2020
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);
}
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);
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)
Huh? What's going on here? Why bother with the == true
part? Let's simplify that.
if (flag)
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())
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.
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
November 26, 2024