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

前端 未结 2 1374
渐次进展
渐次进展 2020-12-05 09:16

Suppose I have:

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

I want to pass the Value member as an out parameter like

2条回答
  •  一生所求
    2020-12-05 09:58

    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.

提交回复
热议问题