This doesn't work
public class Foo {
private int X { get; }
public Foo(string s) {
int.TryParse(s, out X);
}
}
but this works:
public class Foo {
private int X { get; }
public Foo(string s) {
int x;
int.TryParse(s, out x);
X = x;
}
}
What is the difference between the two, since the out parameter doesn't need to be initialised. Why the property cannot be passed as an out parameter?
I assume this is C# 6.0 because you have a get-only property.
It doesn't work because properties cannot be passed by reference. A function that takes a ref int or an out int parameter in C# is like a function that takes an int& in C++.
But an int property is not just an int at some address. A property can run any code it wants to in both the get and the set. And the language should not treat an auto-implemented property as special.
What if I wrote code like the following?
public class Foo {
private int X {
get { return 0; }
set { }
}
public Foo(string s) {
int.TryParse(s, out X);
}
}
There simply isn't any address of an int to pass into TryParse. The rules for whether the code is allowable are not permitted to look inside the get and set implementations.
Note that this works fine:
public class Foo {
private int X;
public Foo(string s) {
int.TryParse(s, out X);
}
}
When you use out, under the hood it's really a memory address that gets passed to the function that you call. A property is not a variable but a function and you cannot take its address so a property cannot be passed in place of an out parameter.
A member variable (or local variable) occupies memory and the compiler can take their address and pass it so it works with variables but not with properties.
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