Search code examples
returnblazor

return object after null checking through if


public async Task<ServiceResponse<Product>> GetProductAsync(int productId)
{
    var response = new ServiceResponse<Product>()
    {
        Data = await _context.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == productId)
    } ;

    if ( response.Data == null )
    {
        response.Success = false ;
        response.Message = "Sorry, but this product does not exist." ;
    }
    else
        return response ;

    return response ;
}

I made productservice.cs file. The above code is the part of it which will return one product class in Gerelic T.

First, I find matched productid in db. Then, null check. If it is not null it will return response, OK.

I thought at first I will return response as one product to Task T, all code might be good.

But I faced an error in the last line, so I put again return response. Then the error sign was disappeared.

I think this might be wrong and weird, even though there is no error anymore. How can I solve this problem efficiently?


Solution

  • The error you faced probably was something like not all code paths return a value. Since your method returns a typed value, and you are using if-else statement -- you have to provide returning value both in if and else clauses.

    1. Extend your ServiceResponse<T> with a constructor that receives some arguments.
    2. Refactor your method in order to stress your product variable for better readability.
    3. Return ServiceResponse using newly-created constructor.

    Unfortunately, I can't test it right now to be sure 100%, but you can give it a try.

    class ServiceResponse<T>
    {
        public T Data { get; set; }
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
    
        public ServiceResponse( T data, string message = "success" )
        {
            Data = data;
            IsSuccess = data != null;
            Message = data == null ? "Sorry, but this product does not exist." : message;
        }
    }
    
    
    public async Task<ServiceResponse<Product>> GetProductAsync( int productId )
    {
       var product = await _context.Products.Where( p => p.Id == productId).AsNoTracking().FirstOrDefault();
       return new ServiceResponse<Product>( product );
    }
    

    Remarks

    1. We don’t have to provide 2nd argument into the constructor while returning the response since it already has the default value defined for the message in the constructor. But you still can do that!
    2. I also set default value for the message there if data == null. Actually, it can be removed if you wish!
    3. IsSuccess is also being regulated by data in the constructor of ServiceResponse<T>

    UPD: Tested

    if ProductId == 1
    
    {
      "data": {
        "id": 1,
        "name": "Test1"
      },
      "isSuccess": true,
      "message": "success"
    }
    

    if ProductId == 2 (which is out of list)
    
    {
      "data": null,
      "isSuccess": false,
      "message": "Sorry, but this product does not exist."
    }