C# – Difference between ref and out parameters in .NET


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?

Best 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.