[ACCEPTED]-Best practice of using the "out" keyword in C#-.net

Accepted answer
Score: 22

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

Score: 19

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

Avoid using out or reference parameters.

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

But 2 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 1 method signature easier to understand.

Score: 6

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


as opposed 3 to

DoThing(a, out b);

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

Score: 4

There are only very few cases where I would 14 use out. One of them is if your method returns 13 two variables that from an OO point of view 12 do not belong into an object together.

If 11 for example, you want to get the most common 10 word in a text string, and the 42nd word 9 in the text, you could compute both in the 8 same method (having to parse the text only 7 once). But for your application, these informations 6 have no relation to each other: You need 5 the most common word for statistical purposes, but 4 you only need the 42nd word because your 3 customer is a geeky Douglas Adams fan.

Yes, that 2 example is very contrived, but I haven't got 1 a better one...

Score: 2

I just had to add that starting from C# 7, the 12 use of the out keyword makes for very readable code 11 in certain instances, when combined with 10 inline variable declaration. While in general 9 you should rather return a (named) tuple, control flow 8 becomes very concise when a method has a 7 boolean outcome, like:

if (int.TryParse(mightBeCount, out var count)
    // Successfully parsed count

I should also mention, that 6 defining a specific class for those cases 5 where a tuple makes sense, more often than 4 not, is more appropriate. It depends on 3 how many return values there are and what 2 you use them for. I'd say, when more than 1 3, stick them in a class anyway.

Score: 1

Stay away from out. It's there as a low-level 2 convenience. But at a high level, it's an 1 anti-technique.

int? i = Util.TryParseInt32("1");
if(i == null)
Score: 1

One advantage of out is that the compiler will 3 verify that CalcSomething does in fact assign a value 2 to someOtherNumber. It will not verify that the someOtherNumber 1 field of Result has a value.

Score: 1

If you have even seen and worked with MS namespace 13 System.Web.Security

   public abstract MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status);

You will need a bucket. This 12 is an example of a class breaking many design 11 paradigms. Awful!

Just because the language 10 has out parameters doesn't mean they should 9 be used. eg goto

The use of out Looks more 8 like the Dev was either Lazy to create a 7 type or wanted to try a language feature. Even 6 the completely contrived MostCommonAnd42ndWord example above 5 I would use List or a new type contrivedresult 4 with 2 properties.

The only good reasons 3 i've seen in the explanations above was 2 in interop scenarios when forced to. Assuming 1 that is valid statement.

Score: 0

You could create a generic tuple class for 12 the purpose of returning multiple values. This 11 seems to be a decent solution but I can't 10 help but feel that you lose a bit of readability 9 by returning such a generic type (Result is no 8 better in that regard).

One important point, though, that 7 james curran also pointed out, is that the 6 compiler enforces an assignment of the value. This 5 is a general pattern I see in C#, that you 4 must state certain things explicitly, for 3 more readable code. Another example of this 2 is the override keyword which you don't 1 have in Java.

Score: 0

If your result is more complex than a single 20 value, you should, if possible, create a 19 result object. The reasons I have to say 18 this?

  1. The entire result is encapsulated. That 17 is, you have a single package that informs 16 the code of the complete result of CalcSomething. Instead 15 of having external code interpret what the 14 decimal return value means, you can name 13 the properties for your previous return 12 value, Your someOtherNumber value, etc.

  2. You 11 can include more complex success indicators. The 10 function call you wrote might throw an exception 9 if end comes before start, but exception 8 throwing is the only way to report errors. Using 7 a result object, you can include a boolean 6 or enumerated "Success" value, with appropriate 5 error reporting.

  3. You can delay the execution 4 of the result until you actually examine 3 the "result" field. That is, the execution 2 of any computing needn't be done until you 1 use the values.

More Related questions