TryXXX-like methods with "out" parameters versus returning a null type?

I often see similar methods in C #: (a calculation that may or may not produce a result)

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

Why don't people use something like this instead?

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

Is it just a performance difference? This is a struct , so there shouldn't be a heap, right? Or am I missing something?

+4
source share
1 answer

Nullable was introduced - as generics - in C # 2.0. There is a lot of code that precedes this.

And to be honest, I'm not a big fan of just returning Nullable when something can go wrong.

You usually have a method like

 SomeOtherType Something(SomeType inputData) { ... } 

which throws 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, the exception is accurate in what went wrong, the logical value is not. So if it gives you false , you have little information that "it did not work." In some cases, this may be sufficient. I like to distinguish the error "My collection does not contain this value" because of the error "I have run out of memory and can’t do anything else" or something else.

Now, introducing the Nullable value as the return value, this is - as I call it - knowledge of the druid, to know that getting null does not mean "The value is null", but "some error occurred." This is what you will need to document and explain, and the bool result of the TryXXX method is self-explanatory.

In short, you are not getting anything, but you are creating somewhat more confusing code, using Nullable as the return value.

+1
source

Source: https://habr.com/ru/post/1490060/


All Articles