C# 9 records validation

C# 9 records validation

C# 9 records provide an easy way to create immutable objects with built-in equality and hash code generation. If you want to enforce validation rules on the properties of a record, you can do so using the built-in constructor or a separate validation method. Here are some examples:

public record Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
    public int Age { get; init; }

    public Person(string firstName, string lastName, int age)
    {
        if (string.IsNullOrWhiteSpace(firstName))
            throw new ArgumentException("First name cannot be null or empty", nameof(firstName));

        if (string.IsNullOrWhiteSpace(lastName))
            throw new ArgumentException("Last name cannot be null or empty", nameof(lastName));

        if (age <= 0)
            throw new ArgumentException("Age must be a positive integer", nameof(age));

        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }
}

In this example, the constructor of the Person record checks the validity of the input parameters and throws an exception if any of the validation rules are violated. You can create an instance of the Person record as follows:

var person = new Person("John", "Doe", 30);

If any of the input parameters violate the validation rules, an exception will be thrown.

Alternatively, you can define a separate validation method that validates the properties of the record, and call this method from the constructor:

public record Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
    public int Age { get; init; }

    public void Validate()
    {
        if (string.IsNullOrWhiteSpace(FirstName))
            throw new ArgumentException("First name cannot be null or empty", nameof(FirstName));

        if (string.IsNullOrWhiteSpace(LastName))
            throw new ArgumentException("Last name cannot be null or empty", nameof(LastName));

        if (Age <= 0)
            throw new ArgumentException("Age must be a positive integer", nameof(Age));
    }

    public Person(string firstName, string lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;

        Validate();
    }
}

In this example, the Person record defines a separate Validate() method that checks the validity of the properties. The constructor of the record calls the Validate() method after setting the properties. You can create an instance of the Person record as follows:

var person = new Person("John", "Doe", 30);
person.Validate();

If any of the properties violate the validation rules, the Validate() method will throw an exception.

Overall, C# 9 records provide a convenient way to define immutable objects with built-in equality and hash code generation, while still allowing you to enforce validation rules on the properties of the record.

Examples

  1. "C# 9 Records Validation with Constructor"

    • Code Implementation:
      public record Person
      {
          public string Name { get; init; }
          public int Age { get; init; }
      
          public Person(string name, int age)
          {
              if (string.IsNullOrEmpty(name))
                  throw new ArgumentException("Name cannot be null or empty.", nameof(name));
      
              if (age < 0)
                  throw new ArgumentOutOfRangeException(nameof(age), "Age must be a non-negative value.");
      
              Name = name;
              Age = age;
          }
      }
      
    • Description: Demonstrates record validation using constructor parameters, throwing exceptions for invalid values.
  2. "C# 9 Records Validation with Property Setter"

    • Code Implementation:
      public record Person
      {
          private string _name;
          public string Name
          {
              get => _name;
              init
              {
                  if (string.IsNullOrEmpty(value))
                      throw new ArgumentException("Name cannot be null or empty.", nameof(Name));
      
                  _name = value;
              }
          }
      
          public int Age { get; init; }
      }
      
    • Description: Shows record validation using property setters to enforce constraints during assignment.
  3. "C# 9 Records Validation with Method"

    • Code Implementation:
      public record Person
      {
          public string Name { get; init; }
          public int Age { get; init; }
      
          public Person WithAge(int age)
          {
              if (age < 0)
                  throw new ArgumentOutOfRangeException(nameof(age), "Age must be a non-negative value.");
      
              return this with { Age = age };
          }
      }
      
    • Description: Utilizes a validation method (WithAge) to enforce constraints during record modification.
  4. "C# 9 Records Validation Attribute"

    • Code Implementation:
      [AttributeUsage(AttributeTargets.Property)]
      public class ValidateNameAttribute : ValidationAttribute
      {
          public override bool IsValid(object value)
          {
              if (value is string name && !string.IsNullOrEmpty(name))
                  return true;
      
              return false;
          }
      }
      
      public record Person
      {
          [ValidateName(ErrorMessage = "Name cannot be null or empty.")]
          public string Name { get; init; }
      
          public int Age { get; init; }
      }
      
    • Description: Introduces a custom validation attribute (ValidateNameAttribute) for property-level validation.
  5. "C# 9 Records Validation with FluentValidation"

    • Code Implementation:
      public class PersonValidator : AbstractValidator<Person>
      {
          public PersonValidator()
          {
              RuleFor(person => person.Name)
                  .NotEmpty()
                  .WithMessage("Name cannot be null or empty.");
      
              RuleFor(person => person.Age)
                  .GreaterThanOrEqualTo(0)
                  .WithMessage("Age must be a non-negative value.");
          }
      }
      
      public record Person
      {
          public string Name { get; init; }
          public int Age { get; init; }
      }
      
    • Description: Uses FluentValidation library to define validation rules for record properties.
  6. "C# 9 Records Validation with INotifyDataErrorInfo"

    • Code Implementation:
      public record Person : INotifyDataErrorInfo
      {
          private string _name;
          public string Name
          {
              get => _name;
              init
              {
                  if (string.IsNullOrEmpty(value))
                      AddError(nameof(Name), "Name cannot be null or empty.");
                  else
                      RemoveError(nameof(Name));
      
                  _name = value;
              }
          }
      
          public int Age { get; init; }
      
          // Implement INotifyDataErrorInfo methods...
      }
      
    • Description: Implements INotifyDataErrorInfo to provide validation errors for data binding scenarios.
  7. "C# 9 Records Validation with Guard Clauses"

    • Code Implementation:
      public record Person
      {
          private string _name;
          public string Name
          {
              get => _name;
              init
              {
                  Guard.AgainstNullOrEmpty(value, nameof(Name), "Name cannot be null or empty.");
                  _name = value;
              }
          }
      
          public int Age { get; init; }
      }
      
    • Description: Integrates guard clauses for concise validation in record properties.
  8. "C# 9 Records Validation with Data Annotations"

    • Code Implementation:
      public record Person
      {
          [Required(ErrorMessage = "Name cannot be null or empty.")]
          public string Name { get; init; }
      
          [Range(0, int.MaxValue, ErrorMessage = "Age must be a non-negative value.")]
          public int Age { get; init; }
      }
      
    • Description: Utilizes Data Annotations for declarative validation on record properties.
  9. "C# 9 Records Conditional Validation"

    • Code Implementation:
      public record Person
      {
          public string Name { get; init; }
      
          public int? Age { get; init; }
      
          public bool IsValid => !string.IsNullOrEmpty(Name) && (Age.HasValue && Age >= 0);
      }
      
    • Description: Introduces a conditional validation property (IsValid) based on the values of other properties.
  10. "C# 9 Records Validation in Immutable Collections"

    • Code Implementation:
      public record Order
      {
          public string OrderId { get; init; }
          public IEnumerable<string> Products { get; init; } = Array.Empty<string>();
      
          public Order WithProducts(IEnumerable<string> products)
          {
              if (products == null || !products.Any())
                  throw new ArgumentException("Order must have at least one product.");
      
              return this with { Products = products };
          }
      }
      
    • Description: Demonstrates validation in records with immutable collections, ensuring non-null and non-empty products.

More Tags

automata angular-datatables c#-5.0 checked postgresql-9.4 dart-http pointers lemmatization keil podfile

More C# Questions

More Date and Time Calculators

More Biochemistry Calculators

More Math Calculators

More Pregnancy Calculators