C#C
C#3y ago
Dyad

❔ Maybe Disposable Object

I want to have a function that returns an HttpClient or an error. The function would take in JSON API user credentials and return an HttpClient with the Base Address and Authorization Headers set if the credentials are valid, otherwise an error message. When consuming this function I was going to use a using statement:

using(var client = MakeNewClient(username, password))
{
}

or...

var clientOrError = MakeNewClient(username, password);
if(client.Error != null)
return;

using(clientOrError.client)
{
}

What should the return type of MakeNewClient() be in order to surface the error and still be able to use it in a using statement? Or is my approach to this wrong all-together?
Was this page helpful?