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.
"C# 9 Records Validation with Constructor"
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; } }
"C# 9 Records Validation with Property Setter"
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; } }
"C# 9 Records Validation with Method"
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 }; } }
WithAge
) to enforce constraints during record modification."C# 9 Records Validation Attribute"
[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; } }
ValidateNameAttribute
) for property-level validation."C# 9 Records Validation with FluentValidation"
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; } }
"C# 9 Records Validation with INotifyDataErrorInfo"
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... }
INotifyDataErrorInfo
to provide validation errors for data binding scenarios."C# 9 Records Validation with Guard Clauses"
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; } }
"C# 9 Records Validation with Data Annotations"
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; } }
"C# 9 Records Conditional Validation"
public record Person { public string Name { get; init; } public int? Age { get; init; } public bool IsValid => !string.IsNullOrEmpty(Name) && (Age.HasValue && Age >= 0); }
IsValid
) based on the values of other properties."C# 9 Records Validation in Immutable Collections"
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 }; } }
automata angular-datatables c#-5.0 checked postgresql-9.4 dart-http pointers lemmatization keil podfile