C# C# Streams and Data Processing Parsing Data Working with DateTime

Ranvir Sahota
Ranvir Sahota
9,844 Points

Why can't a property be used in out for TryParse?

I tried to do it in visual studio and it came up with an error "A property or indexer may not be passed as an out or ref parameter." https://stackoverflow.com/questions/27085696/autoproperty-as-out-value So far the top answer is the best explanation I've seen so far. I would like to get a second opinion and hear if anyone else has any idea why they did this. Thanks

1 Answer

Steven Parker
Steven Parker
187,496 Points

The SO explanation seems to cover it. An out (or ref) needs to be associated with a place to store something but a property represents a set of methods for getting and setting a value. So there's really nothing the compiler can do to make this work. But it's easy enough to get around, for example, assuming an int type:

int result;
if (int.TryParse(MyString, out result))
    MyProperty = result;
Ranvir Sahota
Ranvir Sahota
9,844 Points

ok thanks, I was reading through some c# documentation to help my understanding and you can do this now in 7.0:

if (int.TryParse(MyString, out int result)) MyProperty = result;