DEV Community

QuillCodes
QuillCodes

Posted on • Originally published at quill.codes

3 1

Set Class Fields Using 'out' Parameters

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.

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.

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));
    }
  }
}

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs