+ 3
C# ref vs out parameters
Is there any real advantage or best practise using out instead of ref parameters (except the fact one does not have to initialize out arguments)? Thanks.
3 Réponses
+ 2
Another difference is that "ref" provides both in and out functionality, while "out" as the word says provides only out functionality. Yet ref requires the variable to be initialized before being passed, which can be an important difference in the context of Marshaling (Interop: UmanagedToManagedTransition or vice versa). Use out to denote that the parameter is not being used, only set. This helps the caller understand that you're always initializing the parameter. Also if you write code that could be used by someone else, it could be easier to read and understand, because if I read "out" in a method I quickly understand that you're only need to set this variable.
Hope this image helps you to understand the differences between them.
https://i.stack.imgur.com/T9uaK.png
D.
+ 1
So the main reason to inject a brand new keyword into a language was the ability to denote somehing? Maybe I miss something important, but I suppose that in 99 % “ref” can do the same job as “out” can. I was looking for the rest 1 %, anyway thank you for your detailed explanation of functionality, appreciate it.
0
yes of course ref can do everything out can do. it’s out that cannot do everything ref can do in fact it’s quite less expensive if we talk anout resources. so if i can suggest you a thing, if you only need to pass a variable that need to be modified by the method you can almost always use “out”