Are there any principles to keep in mind when using out parameters? Or can I look at them as just a good way to let a method return multiple values?
What did the language designers have in mind when they were specifying the out parameter?
Edit after some thought:
As i'm thinking about it now, I would be inclined to say that excessive use of out parameters could be indicitive of a code-smell. If a method needs to return instances of more than 1 specific type it implies that the method has more than 1 concern, which is a violation of SRP.
Using out parameters at all is generally bad practice. It typically indicates a method that is doing more than one well defined thing. The only time I recommend using them is for Interop scenarios where they are sometimes necessary because of the signature of the API.
The class design tools specifically say to "Avoid out parameters", with a long discussion for the rationale.
Unless there is a good reason to use an out parameter for a method, it is typically better to make a custom class or struct to hold your results. Using out parameters reduces the usability of an API.
I often use nullable types when returning value types plus an indicator of success rather than returning a bool and using an out parameter for the value type. I even wrap the TryParse method so that it returns a nullable.
Out parameters are bad also because they must use local variables or fields. You can't easily refactor your code to use properties.
It's almost always best to create a custom class/struct, use tuples or nullable types.
While
out
parameters have their use, before using one you should stop and think if you really need it. You may be able to come up with a simpler, cleaner implementation that does not requireout
.why-are-out-parameters-in-net-a-bad-idea has more information.