TryXXX-like methods with “out” parameters vs returning a nullable value type?

守給你的承諾、 提交于 2019-12-10 15:34:53

问题


I often see methods like this in C#: (doing a computation that may or may not give a result)

bool TrySomething(SomeType inputData, out SomeOtherType result) { ... }

Why people don't use instead something like this?

Nullable<SomeOtherType> TrySomething(SomeType inputData) { ... }

Is it just performance difference? This is a struct, so there must be no heap allocation, right? Or I have missed something?


回答1:


Nullable was introduced - like generics - in C# 2.0. There is a lot of code that predates that.

And to be honest, I am not a big fan of just returning a Nullable whenever something can go wrong.

What you usually have is a method like

SomeOtherType Something(SomeType inputData) { ... }

which will throw an exception if something goes wrong. Now in some cases, you want to avoid an exception, so there is an alternative way: the one you gave.

bool TrySomething(SomeType inputData, out SomeOtherType result) { ... }

However, an exception is precise in what went wrong, a boolean value isn't. So if it gives you false, you have little more information that "It didn't work". In some cases, that might be enough. Me, I like to distinguish a "My collection did not contain that value" error from a "I am currently running out of memory and cannot do anything anymore" error, or whatever else.

Now introducing the Nullable as return value, it is - as I call it - druid knowledge to know that receiving null doesn't mean "The value is null", but "Some error occurred". That is something you would need to document and explain, while the bool result of a TryXXX method is self-explanatory.

In short, you gain nothing but produce slightly more confusing code by using Nullable as a return value.



来源:https://stackoverflow.com/questions/17505958/tryxxx-like-methods-with-out-parameters-vs-returning-a-nullable-value-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!