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.
Ref and out parameters are used to pass an argument within a method. Ref and out will change the behavior of function parameters. Sometimes we want the actual value of a variable to be copied as the parameter.
What are the differences between ref and out parameters in C#? A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters.
The compiler demands that an out parameter be "definitely assigned" before exit from the method. There is no such restriction with the ref type. 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.
"It's not possible to have a ref or out value as a field in a class." --The compiler could easily implement ref parameters to iterators by allocating a single element array in the caller, putting the argument into that, and passing the array to the iterator, and having the iterator operate on array [0].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With