HiveBrain v1.2.0
Get Started
← Back to all entries
gotchacsharpCritical

Difference between ref and out parameters in .NET

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
netandbetweendifferencerefoutparameters

Problem

What is the difference between ref and out parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?

Solution

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.

Code Snippets

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

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

Context

Stack Overflow Q#135234, score: 511

Revisions (0)

No revisions yet.