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!
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:
TryGet or TryParse function is false, then the user should not use the out content.bool TryGetMessage(string key, [NotNullWhen(true)] out string? message) (more info here)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).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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With