Custom Validation Interface: If you need a boolean-style validation method, consider creating a custom interface like IValidatable with a bool IsValid method for implementation by relevant classes.
Here's an example of using a custom validation interface in C#:
1. Define the Interface:
public interface IValidatable
{
bool IsValid { get; }
}
This interface defines a single property IsValid
that returns a boolean value indicating the validity of the implementing object.
2. Implement the Interface:
public class Person : IValidatable
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsValid
{
get
{
return !string.IsNullOrEmpty(Name) && Age >= 18;
}
}
}
The Person
class implements the IValidatable
interface and provides its own implementation for the IsValid
property. This property checks for a non-empty name and age greater than or equal to 18, returning true if both conditions are met.
3. Usage with Validation Utility:
public static class ValidationUtil
{
public static void Validate(IValidatable obj)
{
if (!obj.IsValid)
{
throw new ValidationException("Object is not valid.");
}
}
}
public class Example
{
public void ValidatePerson(Person person)
{
ValidationUtil.Validate(person);
// Only proceed if validation passes
Console.WriteLine("Person is valid: {0}", person.Name);
}
}
The ValidationUtil
class defines a Validate
method that accepts an IValidatable
object. This method throws a ValidationException
if the object's IsValid
property is false.
The Example
class demonstrates how to use the ValidatePerson
method with a Person
object. This method first validates the person using ValidationUtil.Validate
and then proceeds only if the validation passes.
Benefits:
ValidationUtil
class provides a central location for handling validation logic, promoting code consistency.This example provides a basic framework for utilizing custom validation interfaces in C#. You can further extend this concept by adding additional validation rules or creating different validation interfaces for specific purposes.