Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practice for Output parameter in C#

Tags:

c#

I have been a C/C++ programmer and new to C#.

I want to return multiple params from a function along with status, so I want to use them as output params. Here is an example.

bool SomeFunction(string inStr, out string outStr)
{
    if (someCondition)
    {
        outStr = AnotherFunction(inStr);
        return true;
    }
    return false;
}

I want to set value of outStr only based on some condition and not always. However, it does not compile and I have to initialize outStr with some value like below.

bool SomeFunction(string inStr, out string outStr)
{
    outStr = string.Empty; // this makes it compile
    if (someCondition)
    {
        outStr = AnotherFunction(inStr);
        return true;
    }
    return false;
}

I am looking to not initialize it if some condition fails. In that case, I want to return with an error without initializing. I know it is possible with keyword ref instead of out and I know the difference between ref and out. Is use of ref in such use case a good practice? What are the best practices for output params in a function. Thanks in advance!

like image 975
ank Avatar asked Oct 27 '25 05:10

ank


1 Answers

The C# community is petty divided on out parameters, usually because a good signature is a signature with as few parameters as possible and out parameters can always be converted in returned types.

But sometimes they are useful and can still create good looking code.

My best practices:

  • Out parameters are always initialized. If the result of the TryGet or TryParse function is false, then the user should not use the out content.
  • Attributes come in handy in these cases, if you want to leave the out parameter null and you'd like the compiler to help you out: bool TryGetMessage(string key, [NotNullWhen(true)] out string? message) (more info here)
  • If you have more than 1 out parameter or if the function is more complex than the one you posted, return an object. It is easier to maintain, to read and to test.
  • In the case an object seems too much of a commitment (maybe it would only be used once) you can use a tuple. Don't overdo with them though, readability might suffer.
  • bool + out pattern is universally recognized. If you want to "return an error" with it, maybe this is not what you are looking for (a hard GetXOrThrow() might be what you are looking for).
  • I wouldn't use ref in your case. use ref when you want the value to be modified as a side effect. In this case, outStr is definitely a new variable.
like image 98
Alvin Sartor Avatar answered Oct 29 '25 22:10

Alvin Sartor