class LetMeOut { // You can assign class fields with 'out' parameters private readonly int _fieldAssign;
public LetMeOut(string data) { if (!Int32.TryParse(data, out _fieldAssign)) throw new ArgumentException("Invalid data", nameof(data)); } }

Set Class Fields Using 'out' Parameters

Casey McQuillan
September 17, 2020

Did You Know?

You can set class fields with ‘out’ method parameters

Whether you like out parameters or not in C#, they are here to stay. They decorate a number of common patterns in the .NET ecosystem.

  • The TryParse pattern where the return is a bool that indicates success and your parse result comes from the out parameter.

However, very often you want to set your class field with the parse result. At first you would assume that you need to declare a temporary variable to hold the value and then assign the field.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class MyClass
{
  private int _parsedIntField;

  public MyClass(string strToParse)
  {
    if (!Int32.TryParse(strToParse, out int result))
    {
      throw new ArgumentException("Please provide a valid numerical string.", nameof(strToParse));
    }

    _parsedIntField = result;
  }
}

However, this isn’t necessary. Turns out you can just set the field directly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class MyClass
{
  private int _parsedIntField;

  public MyClass(string strToParse)
  {
    if (!Int32.TryParse(strToParse, out _parsedIntField))
    {
      throw new ArgumentException("Please provide a valid numerical string.", nameof(strToParse));
    }
  }
}