This is NOT a failure of anything. I’m just trying to determine how to write c# more elegantly.
In a C# project I find I am doing an awful lot of
if (null != classX.user || await classX.getUserAsync())
{
// getUserAsync() either sets classX.user appropriately and returns true, or else returns false.
// Calls to classX members and other functions that are only OK when classX.user is valid follow
and I’d like to bundle this into a member function like
private async Task<bool> IsUserSet()
{
if (null != user)
return await Task.FromResult<bool>(user);
return await getUserAsync();
}
because (IMHO) replacing the if statement with if (IsUserSet())
is more readable.
However, I’m wondering if the performance hit (there is one with inserting another Task isn’t there?) is worth it, or if there is a way to do this without inserting another task. I could do
if (classX.user ?? await classX.getUserAsync())
but honestly it doesn’t look much cleaner to me, though maybe it would if I had more experience. (Or maybe I just need some education on how to write cleaner ASP.NET code!)