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
2
Answers
Because
if
requiresbool
, notTask<bool>
retuned byIsPolicyExistInADCAsync
. ChangeValidatePolicy
toasync Task
:Yes, because methods returning tasks do not (usually) return null’s. And async state machine should always result in not-nullable
Task
.Read also:
Task<T>.Result
, also check out info aboutGetAwaiter().GetResult()
)That implies that
IsPolicyExistInADCAsync()
is anasync
method. (The code shown doesn’t include this method, but includes methods similar to it which are themselvesasync
, 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 methodasync
:And
await
the asynchronous operation therein:And of course, anything which calls
ValidatePolicy()
will also need toawait
its result.