Why I don't like Dictionary.TryGetValue and how I made it better (I hope)

The most annoying thing of Dictionary.TryGetValue is that it returns a default value of value parameter if key is not found. E.g. if value is of float type it will be 0.0f.
Because of that you have to check the returned bool and if it’s false you have to assign the value you need. It looks as follows

As you can see now we have to deal with redundant if statement which makes code not so clean and neat as it could be.
How about this one?

Fortunately it’s quite easy to make it real with an extension class like as follows

Share Comments
comments powered by Disqus