skip to Main Content

I am checking two conditions which is following in C#:

 if (result.Data.Count > 0)
 {
     if(result.Data[0].AdditionalData != null)
      {
         // To Do
      }
  } 

My confusion is there is any better way to check these in a single if condition?

I am trying to use Null-Condition operator, but did not work it. Null-Conditional operator in MSDN

5

Answers


  1. You can create extension method on IEnumerable and use it

        public static bool HasValue<T>(this IEnumerable<T> source, int index)
        {
            if (source == null)
                return false;
    
            return source.Count() > index && source.ElementAt(index) != null;
        }
    
    // usage
    if(result.Data.HasValue(0))
    {
    }
    
    Login or Signup to reply.
  2. Like written also by @Hans Killian try to use the extensions already there for IEnumerables
    In your case I think .ElementAtOrDefault(0) (or if you always want to use index 0 just use .FirstOrDefault()) is the best fit for you here.

    if (result?.Data != null)
    {
        /// Expecting 'AdditionalData' is `string`
        if (!string.IsNullOrEmpty(result.Data.ElementAtOrDefault(0)?.AdditionalData))
        {
            Console.WriteLine("Null check working...");
        }
        else
        {
            Console.WriteLine("AdditionalData is null or empty!");
        }
    }
    else
    {
        Console.WriteLine("No data!");
    }
    

    Full working example can be found here

    Login or Signup to reply.
  3. Null conditional can work along with Any, and short-circuiting the next check

    if (result?.Data?.Any() && result.Data[0]?.AdditionalData != null)
    {
        // to do
    }
    

    Explanation of each of the steps

    result?

    Is result not null?

    Data?

    if so, is Data not null?

    Any()

    if so, does Data have any items?

    Data[0]?

    if so, is the first item not null? (the reason I use index here is because you may want to check the nth item, so FirstOrDefault may be too restrictive)

    AdditionalData != null

    if so, is Additional data not null?

    Of course, if any of these checks are unnecessary or superfluous you can remove the specific check from the chain (remove ? in the case of null-conditional). Here the checks are all laid out clearly in one line so it’s simple to modify the chain of logic.

    Login or Signup to reply.
  4. One liner using System.Linq.

    if (result.Data.FirstOrDefault()?.AdditionalDate != null)
    {
     
    } 
    
    Login or Signup to reply.
  5. I think the best way to have clean and good code is to use FluentValidation. Please note the following code snippet:

    public class RegisterValidator : AbstractValidator<RegisterDTO>
    {
        public RegisterValidator()
        {
            RuleFor(a => a.PhoneNumber).NotNull().WithMessage(Utility.GetEnumTitlePersian(enmErrorMessage.InValidMobileNumber));
            RuleFor(a => a.PhoneNumber).NotEmpty().WithMessage(Utility.GetEnumTitlePersian(enmErrorMessage.InValidMobileNumber));
            RuleFor(a => a.PhoneNumber).MinimumLength(11).WithMessage(Utility.GetEnumTitlePersian(enmErrorMessage.InValidMobileNumber));
            RuleFor(a => a.PhoneNumber).MaximumLength(11).WithMessage(Utility.GetEnumTitlePersian(enmErrorMessage.InValidMobileNumber));
        }
    }
    

    The above code is an example of validating a model to check null, empty and etc. and this code must check validation in business logic:

    var validator = new RegisterValidator();
    var validatorResult = await validator.ValidateAsync(register);
    
    if (!validatorResult.IsValid)
        return BadRequest("", validatorResult.Errors[0].ToString());
    

    It is very simple to use and very clean. You can even perform multiple checks and get results through the error list

    This link is the site address of FluentValidation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search