Why ref parameters can not be ignored like out parameters?

3k Views Asked by At

Is there a specific reason why C# 7 bring inlining out parameters but not ref?

The following is valid on C# 7:

int.TryParse("123", out _);

But this is invalid:

public void Foo(ref int x) { }

Foo(ref _); // error

I don't see a reason why the same logic can't be applied to ref parameters.

1

There are 1 best solutions below

1
On BEST ANSWER

The reason is simple: because you're not allowed to pass an uninitialized variable into a ref parameter. This has always been the case, and the new syntactical sugar in C#7 doesn't change that.

Observe:

int i;
MyOutParameterMethod(out i);  // allowed

int j;
MyRefParameterMethod(ref j);  // compile error

The new feature in C#7 allows you to create a variable in the process of calling a method with an out parameter. It doesn't change the rules about uninitialized variables. The purpose of a ref parameter is to allow passing an already-initialized value into a method and (optionally) allow the original variable to be changed. The compiler semantics inside the method body treat ref parameters as initialized variables and out parameters as uninitialized variables. And it remains that way in C#7.