Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are "out" parameters a bad thing in .NET?

Tags:

.net

Are "out" parameters a bad thing in .NET? Any good articles/discussions on this topic?

like image 310
BuddyJoe Avatar asked Nov 11 '08 14:11

BuddyJoe


People also ask

What does an out parameter do?

The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition​ as well as in the calling method.

Do you need to declare an out variable before you use it in C#?

In C# 6 and earlier, you must declare a variable in a separate statement before you pass it as an out argument. The following example declares a variable named number before it is passed to the Int32. TryParse method, which attempts to convert a string to a number.

What does out mean C#?

The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property.

Can we use out parameter in function C#?

C# out parameter is used when a method returns multiple values. When a parameter passes with the Out keyword/parameter in the method, then that method works with the same variable value that is passed in the method call. If variable value changes, the method parameter value also changes.

What is the out keyword parameter modifier in C#?

You can use the out keyword in two contexts: As a parameter modifier, which lets you pass an argument to a method by reference rather than by value. In generic type parameter declarations for interfaces and delegates, which specifies that a type parameter is covariant.


2 Answers

Well, I have an article on what ref/out do - but it doesn't discuss whether or not you should use them.

Basically out parameters are usually a sign that you want to effectively return two results from a method. That's usually a code smell - but there are some cases (most notably with the TryXXX pattern) where you genuinely want to return two pieces of information for good reasons and it doesn't make much sense to encapsulate them together.

In other words, avoid out/ref where you can do so easily, but don't go massively out of your way to avoid them.

like image 97
Jon Skeet Avatar answered Oct 01 '22 03:10

Jon Skeet


For most circumstances I would recommend against using Out parameters. They basically add side-effects to your code and could be a nightmare when it comes to debugging.

There's an article on MSDN regarding Out parameters available here: http://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx

like image 40
Ryan Lanciaux Avatar answered Oct 01 '22 03:10

Ryan Lanciaux