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;
An out-parameter represents information that is passed from the function back to its caller. The function accomplishes that by storing a value into that parameter. Use call by reference or call by pointer for an out-parameter. For example, the following function has two in-parameters and two out-parameters.
The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values.
Calling a method with an out argument In C# 6 and earlier, you must declare a variable in a separate statement before you pass it as an out argument.
No. To make it "optional", in the sense that you don't need to assign a value in the method, you can use ref . A ref parameter is a very different use case.
You'd have to explicitly use a field and "normal" property instead of an auto-implemented property:
public class Bob { private int value; public int Value { get { return value; } set { this.value = value; } } }
Then you can pass the field as an out parameter:
Int32.TryParse("123", out bob.value);
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:
static int ParseOrDefault(string text) { int tmp; int.TryParse(text, out tmp); return tmp; }
Then use:
bob.Value = Int32Helper.ParseOrDefault("123");
That way you can use a single temporary variable even if you need to do this in multiple places.
You can achieve that, but not with a property.
public class Bob { public int Value { get; set; } // This is a property public int AnotherValue; // This is a field }
You cannot use out
on Value
, but you can on AnotherValue
.
This will work
Int32.TryParse("123", out bob.AnotherValue);
But, common guidelines tells you not to make a class field public. So you should use the temporary variable approach.
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