Best practice of using the "out" keyword in C#

There is a reason that one of the static code analysis (=FxCop) rules points at you when you use out parameters. I'd say: only use out when really needed in interop type scenarios. In all other cases, simply do not use out. But perhaps that's just me?


This is what the .NET Framework Developer's Guide has to say about out parameters:

Avoid using out or reference parameters.

Working with members that define out or reference parameters requires that the developer understand pointers, subtle differences between value types and reference types, and initialization differences between out and reference parameters.

But if you do use them:

Do place all out parameters after all of the pass-by-value and ref parameters (excluding parameter arrays), even if this results in an inconsistency in parameter ordering between overloads.

This convention makes the method signature easier to understand.


Your approach is better than out, because you can "chain" calls that way:

DoSomethingElse(DoThing(a,b).Result);

as opposed to

DoThing(a, out b);
DoSomethingElse(b);

The TryParse methods implemented with "out" was a mistake, IMO. Those would have been very convenient in chains.

Tags:

C#

.Net