Difference Between Ref and Out Parameters in .Net

Difference between ref and out parameters in .NET

They're pretty much the same - the only difference is that a variable you pass as an out parameter doesn't need to be initialized but passing it as a ref parameter it has to be set to something.

int x;
Foo(out x); // OK

int y;
Foo(ref y); // Error: y should be initialized before calling the method

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.

What is diffrence between Out type Vs Ref type parameter in C#?

Both indicate to the caller that the method can modify the value of the parameter. out parameters must be initialized inside the method whereas ref parameters might be initialized outside. It's basically a contract. When you see a method that takes an out parameter this means that that caller can invoke it without initializing the value and be sure that it will be initialized inside:

Foo foo;
SomeMethod(out foo);
// at this stage we know that foo will be initialized

whereas with ref:

Foo foo;
SomeMethod(ref foo); // compile time error

It's the caller's responsibility to initialize the variable before calling the method:

Foo foo = new Foo();
SomeMethod(ref foo); // ok

What's the difference between the 'ref' and 'out' keywords?

ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function.

So while ref is two-ways, out is out-only.

What is the difference between ref and out?

ref parameters must be initialized before passing to function,the parameter may or may not be changed by the function.So you need to initialize it before you pass, like you do with non-ref arguments:

int i; 
Foo(i); // error unassigned variable
Foo(ref i) // same error

For out, your function guarantees that it will set the argument to a value.So it doesn't need to be initialized.

When to use in vs ref vs out

You should use out unless you need ref.

It makes a big difference when the data needs to be marshalled e.g. to another process, which can be costly. So you want to avoid marshalling the initial value when the method doesn't make use of it.

Beyond that, it also shows the reader of the declaration or the call whether the initial value is relevant (and potentially preserved), or thrown away.

As a minor difference, an out parameter needs not be initialized.

Example for out:

string a, b;
person.GetBothNames(out a, out b);

where GetBothNames is a method to retrieve two values atomically, the method won't change behavior whatever a and b are. If the call goes to a server in Hawaii, copying the initial values from here to Hawaii is a waste of bandwidth. A similar snippet using ref:

string a = String.Empty, b = String.Empty;
person.GetBothNames(ref a, ref b);

could confuse readers, because it looks like the initial values of a and b are relevant (though the method name would indicate they are not).

Example for ref:

string name = textbox.Text;
bool didModify = validator.SuggestValidName(ref name);

Here the initial value is relevant to the method.

Which is lighter between ref and out parameter in c#

The only difference is a compiler hint.

... out ...

public static void TestOut(out int test)
{
test = 1;
}

.method public hidebysig static void TestOut([out] int32& test) cil managed
{
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: stind.i4
IL_0003: ret
} // end of method Program::TestOut

... ref ...

public static void TestRef(ref int test)
{
test = 1;
}

.method public hidebysig static void TestRef(int32& test) cil managed
{
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: stind.i4
IL_0003: ret
} // end of method Program::TestRef

... out and ref are effectively the same. The only real difference being that out tells the compiler to expect the value to be set before the method is returned. You could send a value to a function that has an out flag but again the compiler will treat it as an unassigned variable. The runtime doesn't really care. Both will be created as a pointer to the variable. You are best to use the keyword that describes the functionality you expect with your function. Any optimization that "may" take place in the JITer below this will have near 0 impact on the application.

What do ref, val and out mean on method parameters?

By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.

void Test1(string param)
{
param = "new value";
}

string s1 = "initial value";
Test1(s1);
// s1 == "initial value"

Using out or ref passes a reference to the variable specified in the call to the function. Any changes to the value of an out or ref parameter will be passed back to the caller.

Both out and ref behave identically except for one slight difference: ref parameters are required to be initialised before calling, while out parameters can be uninitialised. By extension, ref parameters are guaranteed to be initialised at the start of the method, while out parameters are treated as uninitialised.

void Test2(ref string param)
{
param = "new value";
}

void Test3(out string param)
{
// Use of param here will not compile
param = "another value";
}

string s2 = "initial value";
string s3;
Test2(ref s2);
// s2 == "new value"
// Test2(ref s3); // Passing ref s3 will not compile
Test3(out s2);
// s2 == "another value"
Test3(out s3);
// s3 == "another value"

Edit: As dp points out, the difference between out and ref is only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent for out and implements ref (as ByRef) only, matching the support of the CLR.

What is the difference between ref and out

An argument passed to a ref parameter
must first be initialized. Compare
this to an out parameter, whose
argument does not have to be
explicitly initialized before being
passed to an out parameter.

What is diff Between Ref And Out?

  • You use Ref when you pass an initialized parameter and you expect the method/function to modify it.
  • You use Out when you pass an un-initialized parameter and the method will have to initialize and fill that parameter (you get a warning or even error otherwise).

    bool IsUserValid(string username);

    void IsUserValid(string username, out bool valid);

The declarations above are roughly the same. It's easier to return the value, so in this case you will use the return type. But if your method also needs to return the birth date of the user you can't return both parameters in the return, you have to use out parameters to return one of them (or void the method and return both as out).

What is the difference between ref and out? (C#)

For the caller:

  • For a ref parameter, the variable has to be definitely assigned already
  • For an out parameter, the variable doesn't have to be definitely assigned, but will be after the method returns

For the method:

  • A ref parameter starts off definitely assigned, and you don't have to assign any value to it
  • An out parameter doesn't start off definitely assigned, and you have to make sure that any time you return (without an exception) it will be definitely assigned

So:

int x;
Foo(ref x); // Invalid: x isn't definitely assigned
Bar(out x); // Valid even though x isn't definitely assigned
Console.WriteLine(x); // Valid - x is now definitely assigned

...

public void Foo(ref int y)
{
Console.WriteLine(y); // Valid
// No need to assign value to y
}

public void Bar(out int y)
{
Console.WriteLine(y); // Invalid: y isn't definitely assigned
if (someCondition)
{
// Invalid - must assign value to y before returning
return;
}
else if (someOtherCondition)
{
// Valid - don't need to assign value to y if we're throwing
throw new Exception();
}
else
{
y = 10;
// Valid - we can return once we've definitely assigned to y
return;
}
}


Related Topics



Leave a reply



Submit