3

How to simplify the null check

public class MyEmployee
{
    public string FirstName;
    public string LastName;
    public string Age;
    public string Phone;
    public string Gender;
}

I have implemented the following null condition check

public async Task<bool> ValidateClient(MyEmployee Client)
{
    **if(Client.FirstName == null ||Client.LastName==null ||Client.Age== null ||Client.Gender ==null||Client.Phone==null)**
    {
      throw new Argumentexception("Employee details to be provided")
    }
}

I am validating all the properties of Employee class with a null check condition , can this be simplified in C#.

9
  • 4
    Without introducing reflection, this is already about as simple as it gets.
    – Donut
    Commented Feb 21, 2022 at 13:57
  • ValidateClient(MyEmployeeemp) does this compile, what's the definition of MyEmployeeemp and how is Client defined?
    – Trevor
    Commented Feb 21, 2022 at 13:57
  • || Client.LastName || - I doubt that Client.LastName is a boolean value.
    – phuzi
    Commented Feb 21, 2022 at 13:58
  • 4
    If you want to avoid cluttering your code with these checks, just add a method to the Employee class named IsValid() that do all the checks required and return just a true/false
    – Steve
    Commented Feb 21, 2022 at 14:02
  • 1
    @Steve Yep. And if Employee were a "real class" rather than a container for user input, its constructor would validate it. Commented Feb 21, 2022 at 14:23

2 Answers 2

10

Since you're using asp.net core, you'll have the option to validate you model by decorating the properties:

public class MyEmployee
{
    [Required]
    public string FirstName;
    [Required]
    public string LastName;
    [Required]
    public string Age;
    [Required]
    public string Phone;
    [Required]
    public string Gender;
}

if you have that, you can validate the model from within a HTTP action call.

public async Task<IActionResult> OnPostAsync(MyEmployee model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest();
    }
    await yourUpdate();
    return Ok();
}

Note: this only works when you're using the model binders, which are enabled by default in the MVC and API actions.

There are various validation attributes available. Adding for example StringLength gives you the option to validate also for a length > 0.

Various defaults and regex options are available as well.

It puts the validation close to your model and leave you with a nice clean ActionResult method.

Also see Microsoft docs

More build in attributes:

Built-in attributes

Here are some of the built-in validation attributes:

  • [ValidateNever]: Indicates that a property or parameter should be excluded from validation.
  • [CreditCard]: Validates that the property has a credit card format. Requires jQuery Validation Additional Methods.
  • [Compare]: Validates that two properties in a model match.
  • [EmailAddress]: Validates that the property has an email format.
  • [Phone]: Validates that the property has a telephone number format.
  • [Range]: Validates that the property value falls within a specified range.
  • [RegularExpression]: Validates that the property value matches a specified regular expression.
  • [Required]: Validates that the field isn't null. See [Required] attribute for details about this attribute's behavior.
  • [StringLength]: Validates that a string property value doesn't exceed a specified length limit.
  • [Url]: Validates that the property has a URL format.
  • [Remote]: Validates input on the client by calling an action method on the server. See [Remote] attribute for details about this attribute's behavior.

There are tons of these, and you can even build them yourself as well.

2
  • I like this approach, but the Required attribute only validates the field for null, what if that field is just empty? I guess the OP maybe should clarify this as it could be a difference whether or not this would be ideal.
    – Trevor
    Commented Feb 21, 2022 at 14:09
  • 1
    Good point, I'll add a thing about the other validators
    – Stefan
    Commented Feb 21, 2022 at 14:13
2

With Linq you can separate data from operation

if(new[] { Client.FirstName, Client.LastName, ..., Client.Phone }
   .Any(field => field is null))
  • First you define a collection of strings by listing all the string properties of your DTO
  • Then you perform a simple null check against the previous collection for each element

UPDATE #1: Checking for empty string as well

if(new[] { Client.FirstName, Client.LastName, ..., Client.Phone }
   .Any(string.IsNullOrEmpty))
  • In order to test against null or empty string you can utilize the string's IsNullOrEmpty static method
  • If you want to test against whitespaces as well then prefer string.IsNullOrWhitespace
  • The above Any is short form of .Any(field => string.IsNullOrEmpty(field))
3
  • 1
    Nice creative alternative
    – Stefan
    Commented Feb 21, 2022 at 15:12
  • 1
    @Peter Csala can i check null and empty stirng together here
    – jubi
    Commented Feb 22, 2022 at 7:31
  • @jubi Yes, you can. I've updated my post, please check it Commented Feb 22, 2022 at 7:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.