Home > Mobile >  Return two models in a function
Return two models in a function

Time:08-12

I'm trying to return two different models at the same function in C#, I don't know if it's possible.

public async Task<<Model1>, <Model2>> GetLocation()
    {
        string url = Utils.LimbleConnection.SetUrl("/locations");
        try
        {
           return Model1;
        } catch (HttpRequestException httpEx)
        {
           return Model2
        }
    }

CodePudding user response:

Perhaps setting up to return both models. On success, the first item is true, second has the first model, third as null and vis versa for failure. On failure the code below returns a new instance of the model, you need to decide what the data comes back as e.g. populated with whatever you want.

Here I'm simply doing a proof of concept with Entity Framework, you can adapt to your web code.

public static async Task<(bool success, Customer customers, ContactTypes)> GetDataAsync()
{
    try
    {
        await using var context = new CustomerContext();
        return (true, context.Customer.FirstOrDefault(), null);
    }
    catch (Exception exception)
    {
        // log exception then return results
        return (false, null, new ContactTypes());
    }
}

Caller code deconstructs the method.

public async Task Demo()
{
    var (success, customers, contactTypes) = await DataOperations.GetDataAsync();
    if (success)
    {
        // use customers
    }
    else
    {
        // use contact type
    }
}

CodePudding user response:

You can try using a Tuple:

    private Tuple<string, int> Method()
    {
        var tuple = new Tuple<string, int>("String Value", 0);

        return tuple;
    }
  • Related