Suppose I have:
public class Bob
{
public int Value { get; set; }
}
I want to pass the Value member as an out parameter like
Int32.TryParse("123", out bob.Value);
but I get a compilation error, "'out' argument is not classified as a variable." Is there any way to achieve this, or am I going to have to extract a variable, à la:
int value;
Int32.TryParse("123", out value);
bob.Value = value;
You can achieve that, but not with a property.
You cannot use
out
onValue
, but you can onAnotherValue
.This will work
But, common guidelines tells you not to make a class field public. So you should use the temporary variable approach.
You'd have to explicitly use a field and "normal" property instead of an auto-implemented property:
Then you can pass the field as an out parameter:
But of course, that will only work within the same class, as the field is private (and should be!).
Properties just don't let you do this. Even in VB where you can pass a property by reference or use it as an out parameter, there's basically an extra temporary variable.
If you didn't care about the return value of
TryParse
, you could always write your own helper method:Then use:
That way you can use a single temporary variable even if you need to do this in multiple places.