Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
How to check if parameters are null when using positional record constructors and/or init properties?

I would like check no null parameters are assigned to record fields and let the properties have comments. I have found out the following arrangement does the trick for comments, but I lack ideas to check for null parameters without turning this record into a class.

So, a question: Is it possible to check during runtime that nulls won't be assigned to record fields? If so, how could one do it while still using records?

public record Test(string TestString)
{
   /// <summary>
   /// This is one way to get a comment on record properties. Are there others?
   /// </summary>
   public string TestString { get; init; } = TestString;
}

The code is also as a gist here.

This is an addition, but maybe helps with the accepted answer and the comment of different code.

It was because the code in the gist did a null check like

public record Test(string TestString)
{
   /// <summary>
   /// This is one way to get a comment on record properties. Are there others?
   /// </summary>
   public string TestString { get; init; } = TestString ?? throw new ArgumentNullException();
}

For a reason or another, I didn't include this pondering in the original question if there's maybe a shorter way. :)

<edit: The .NET 6 ArgumentNullException.ThrowIfNull(obj) could be handy here (or ThrowHelper).

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You have to handle checks during inline assignment, as you've already discovered in your gist.

One possibility is to call an extension method to wrap any behavior.

public record Test(string TestString)
{
    /// <summary>
    /// This is one way to get a comment on record properties. Are there others?
    /// </summary>
    public string TestString { get; init; } = ValidationExtensions.Validate(TestString);
}

public static class ValidationExtensions
{
    public static string Validate(string input)
    {
        if (string.IsNullOrEmpty(input))
            throw new NullReferenceException();
        
        return input;
    }
}

This will correctly throw during initialization of the record:

var x = new Test(null);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!