Reputation: 625
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#.
Upvotes: 3
Views: 1393
Reputation: 22829
With Linq you can separate data from operation
if(new[] { Client.FirstName, Client.LastName, ..., Client.Phone }
.Any(field => field is null))
string
s by listing all the string properties of your DTOUPDATE #1: Checking for empty string as well
if(new[] { Client.FirstName, Client.LastName, ..., Client.Phone }
.Any(string.IsNullOrEmpty))
string
's IsNullOrEmpty
static methodstring.IsNullOrWhitespace
Any
is short form of .Any(field => string.IsNullOrEmpty(field))
Upvotes: 2
Reputation: 17668
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:
Here are some of the built-in validation attributes:
There are tons of these, and you can even build them yourself as well.
Upvotes: 10