skip to Main Content
private void ValidatePolicy (string PolicyNumber)
{
  var ispolicyvalid = this.IsPolicyExistInADCAsync(PolicyNumber);  
  if(ispolicyvalid) // here I am getting error
  {
    // some logic happens here 
  }
}

This is my code here I am getting an error – cannot implicitly convert type system.threading.tasks.task<bool> to bool.

public async Task<bool> IsPolicyExistAsync(string policyNumber)
{
    var accountId = await this.GetAccountId(policyNumber);
    return accountId != null;
}

public async Task<string> GetAccountId(string accountReference)
{
    // some more logic here

    return accountId;
}

I tried following approaches

Option 1

var ispolicyvalid = this.IsPolicyExistAsync(policyDetails.CorrectPolicyNumber).Result; 

If I try this approach I get another error – replace task.result with await

Option 2

private void ValidatePolicy (string PolicyNumber)
{
  var ispolicyvalid = this.IsPolicyExistInADCAsync(PolicyNumber);  
  if(ispolicyvalid) 
  {
    // some logic happens here 
  }
}

public bool IsPolicyExistAsync(string policyNumber)
{
    var accountId = this.GetAccountId(policyNumber);
    return accountId != null;
}

In this approach there is no error, but ispolicyvalid is always false, because GetAccountId() method still awaiting result hence accountId will not be null value – its false result
Screenshot

2

Answers


  1. I am getting an error – cannot implicitly convert type system.threading.tasks.task to bool

    Because if requires bool, not Task<bool> retuned by IsPolicyExistInADCAsync. Change ValidatePolicy to async Task:

    private async Task ValidatePolicy (string PolicyNumber)
    {
        var ispolicyvalid = await IsPolicyExistInADCAsync(PolicyNumber);  
        if(ispolicyvalid) // here I am getting error
        {
            // some logic happens here 
        }
    }
    

    but ispolicyvalid is always false

    Yes, because methods returning tasks do not (usually) return null’s. And async state machine should always result in not-nullable Task.

    Read also:

    Login or Signup to reply.
  2. cannot implicitly convert type system.threading.tasks.task to bool

    That implies that IsPolicyExistInADCAsync() is an async method. (The code shown doesn’t include this method, but includes methods similar to it which are themselves async, so it’s pretty likely this one is as well.)

    Basically, you would do exactly what the code already does in the IsPolicyExistAsync() method that you’re showing. Make the method async:

    private async Task ValidatePolicy(string PolicyNumber)
    

    And await the asynchronous operation therein:

    var ispolicyvalid = await this.IsPolicyExistInADCAsync(PolicyNumber);
    

    And of course, anything which calls ValidatePolicy() will also need to await its result.

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