I have a basic asynchronous method in one class, which returns an object.
In some of the flows it may fail and I want to report it back.
But I can only return the object.
I tried nullable object, but got the error:
MyObject must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'
I assume I can use exception, but I wanted something simpler in the calling function.
I also cannot use ref
or out
in async methods.
Is there a way to report back some kind of true/false of success or failure?
public static async Task<MyObject> getObject()
{
if (NotOkFromSomeReason())
{
//Not sure what to do here
}
return await myDataBase.FindAsync(something);
}
I call it using:
MyObject object = await getObject();
// I want something simple as if(object)...
Just wrap it into yet another class that will return both desired instance & status code - like:
public class StatusReport
{
public boolean Ok { get; set; }
public MyObject Instance { get; set; }
}
public static async Task<StatusReport> getObject()
{
if (NotOkForSomeReason())
{
return new StatusReport { Ok = false };
}
return new StatusReport { Ok = true, Instance = await myDataBase.FindAsync(something) };
}
If returning null
is an option, you can do:
public static Task<MyObject> getObject()
{
if (NotOkFromSomeReason())
{
return Task.FromResult<MyObject>(null);
}
return myDataBase.FindAsync(something);
}
PS: I'm supposing there's no other code which uses await
in this function, so I've removed async
. Otherwise you can just use the async
qualifier and return null
directly. Since it's returning Task
objects, it's still awaitable from the outside
Then you could check for null
outside:
MyObject myObject = await getObject();
if(myObject == null)
{
}
This will only work if null
is not a possible "correct" result
You could otherwise use exceptions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With