Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,083 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;