Passing a property as an "out" parameter in C #

Suppose I have:

public class Bob { public int Value { get; set; } } 

I want to pass a Value element as an out parameter, e.g.

 Int32.TryParse("123", out bob.Value); 

but I get a compilation error, the argument β€œout” is not classified as a variable. "Is there a way to achieve this, or will I need to extract the variable, Γ  la:

 int value; Int32.TryParse("123", out value); bob.Value = value; 
+66
c # properties
Sep 02 '09 at 21:31
source share
2 answers

You need to explicitly use the field and the β€œnormal” property instead of the property that was automatically implemented:

 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, this will work only in one class, since the field is private (and it should be!).

Properties simply do not allow this. Even in VB, where you can pass a property by reference or use it as an out parameter, basically there is an additional temporary variable.

If you do not need to return a TryParse value, you can 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"); 

This way you can use one temporary variable, even if you need to do it in several places.

+74
Sep 02 '09 at 21:34
source share

You can achieve this, 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 .

It will work

 Int32.TryParse("123", out bob.AnotherValue); 

But in general guidelines, you do not need to publish the class field. Therefore, you should use a temporary variable.

+4
02 Sep '09 at 21:35
source share



All Articles