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

StackOverflow https://stackoverflow.com/questions/17505958

  •  02-06-2022
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top