What is the difference between out and ref




















The out parameter must be initialized inside the called method before it terminates. Declaration The parameter to be altered by a method is declared as ref while method declaration and method calling.

The parameter to be returned must be declared as ref while method declaration and method calling. When we want that the changes made to the arguments inside a called method must reflect in the original value of that variable, then the ref parameter modifier is used. Each time you call a method, it would return a single value only. Sometimes it is the case that when we do not want to pass anything to the method but want the method to return back something we use parameters with an out keyword.

Join our newsletter and get an occasional email with a technology and DotNetPattern. Tags wpf C interview reflection mvvm mvvm light interface generics arraylist hashtable using design patterns visitor template flyweight strategy memento mediator command wcf instance management application architecture ajax angularjs forms validations nested forms filters controllers directives bindings expressions ng-app ng-model environment setup threading synchronization entity framework rhino mocks test doubles oops app android linq testing nunit testcase typescript javascript abstract NumPy.

These keywords are: params ref out By default, method arguments are passed by value. Invalid Email. Successfully subscribed. Email already registered. There is no restriction that called method must work on ref parameter. Called method may not use the ref parameter. Called method must work on out parameter and before returning must initialize the parameter. Skip to content. Change Language. Related Articles. Table of Contents. Save Article. Improve Article.

Like Article. Example :. Sum out G ;. SetValue ref str ;. Out: A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function. Output parameters are like reference parameters, except that they transfer data out of the method rather than into it. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters.

The reference parameters represent the same memory location as the actual parameters that are supplied to the method. In C , you declare the reference parameters using the ref keyword. The following example demonstrates this:. The address in 00 is not altered and retains the reference to FF or the original myList pointer is not disturbed. The ref keyword is a compiler directive to skip the generation of runtime code for 8 and 9 which means there will be no heap allocation for method parameters.

It will use the original 00 pointer to operate on the object at FF. The out keyword is a compiler directive which pretty much is the same as ref with a slight modification at 9 and The compiler expects the argument to be uninitialised and will continue with 8 , 4 and 5 to create an object on heap and to stores its starting address in the argument variable.

No uninitialised error will be thrown and any previous reference stored will be lost. As well as allowing you to reassign someone else's variable to a different instance of a class, return multiple values etc, using ref or out lets someone else know what you need from them and what you intend to do with the variable they provide. You don't need ref or out if all you're going to do is modify things inside the MyClass instance that is passed in the argument someClass.

You need ref or out if you plan on swapping the someClass out for a whole new object and want the calling method to see your change. And they want to know what you're going to do with their data. Imagine you're writing a library that will be used by millions of developers.

You want them to know what you're going to do with their variables when they call your methods. Using ref makes a statement of "Pass a variable assigned to some value when you call my method.

Be aware that I might change it out for something else entirely during the course of my method. Do not expect your variable to be pointing to the old object when I'm done".

Using out makes a statement of "Pass a placeholder variable to my method. It doesn't matter whether it has a value or not; the compiler will force me to assign it to a new value. I absolutely guarantee that the object pointed to by your variable before you called my method, will be different by the time I'm done.

And that prevents the method from swapping out the passed in instance for a different instance. Think of it like saying to those millions of developers "pass me your original variable reference, and I promise not to swap your carefully crafted data out for something else". It can do this because you've declared you're not going to mess with it. By flagging the parameter as out they're actively declaring here "we are definitely going to change your painstakingly crafted value of out for something else".

Of course, they kinda have to, for things like parsing value types because if the parse method wasn't allowed to swap out the value type for something else it wouldn't work very well.. But imagine there was some fictitious method in some library you're creating:. You can see it's an out , and you can thus know that if you spend hours crunching numbers, creating the perfect SomeClass:.

Well that was a waste of time, taking all those hours to make that perfect class. It's definitely going to be tossed away and replaced by PoorlyNamedMethod. At the start of the method, this copy references the original list and therefore can be used to modify this list. So, if a method just modifies the object referenced by the passed variable, the compiler will not let you use out and you should not use ref because it would confuse not the compiler but the reader of the code.

If the method will make the passed argument reference another object, use ref for an already initialized object and out for methods that must initialize a new object for the passed argument. Besides that, ref and out behave the same. They're pretty much the same - the only difference is that a variable you pass as an out parameter doesn't need to be initialised, and the method using the ref parameter has to set it to something. Ref parameters are for data that might be modified, out parameters are for data that's an additional output for the function eg int.

TryParse that are already using the return value for something. Ref: The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out: The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method. Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time CLR doesn't differentiates between the two while it created IL for ref and out.

Below I have shown an example using both Ref and out. Now, you all will be cleared about ref and out. Where to use Ref : when we are calling a procedure with an in parameter and the same parameter will be used to store the output of that proc.

Where to use Out: when we are calling a procedure with no in parameter and teh same param will be used to return the value from that proc. Also note the output. From the standpoint of a method which receives a parameter, the difference between ref and out is that C requires that methods must write to every out parameter before returning, and must not do anything with such a parameter, other than passing it as an out parameter or writing to it, until it has been either passed as an out parameter to another method or written directly.

Note that some other languages do not impose such requirements; a virtual or interface method which is declared in C with an out parameter may be overridden in another language which does not impose any special restrictions on such parameters.

From the standpoint of the caller, C will in many circumstances assume when calling a method with an out parameter will cause the passed variable to be written without having been read first. This assumption may not be correct when calling methods written in other languages. For example:. Note that constructors written in VB. NET, unlike those in C , make no assumptions about whether called methods will modify any out parameters, and clear out all fields unconditionally. The odd behavior alluded to above won't occur with code written entirely in VB or entirely in C , but can occur when code written in C calls a method written in VB.

If you want to pass your parameter as a ref then you should initialize it before passing parameter to the function else compiler itself will show the error. But in case of out parameter you don't need to initialize the object parameter before passing it to the method. You can initialize the object in the calling method itself. Mind well that the reference parameter which is passed inside the function is directly worked on.

I may not be so good at this, but surely strings even though they are technically reference types and live on the heap are passed by value, not reference? This why you need ref if you want changes to exist outside of the scope of the function making them, you aren't passing a reference otherwise.

Stack Overflow for Teams — Collaborate and share knowledge with a private group.



0コメント

  • 1000 / 1000