Returning Multiple Values Using Tuples In C#
Intellisense in visual studio

This example has a helper class, a model class, MVC controller and the view. In the view I will show the string, loop over the list in a foreach loop and display the value from a bool.

Below is the code for the helper class:

Helper class
using System.Collections.Generic;

namespace Web.Helper.TuplesHelper
{
    public class MyDogList
    {
        public IEnumerable<string> DogList()
        {
            List<string> dogs = new List<string> { "German Shepherd", "Siberian Husky", "Bernese Mountain Dog" };

            return dogs;
        }

        public string TestString    = "My favourite dogs is a : ";
        public bool ItsTrue         = true;
    }
}

Now we have the code for the model class:

Model Class
using System.Collections.Generic;

namespace Web.Model.TuplesViewModel
{
    public class TuplesViewModel
    {
        public string TestString                    { get; set; }
        public IEnumerable<string> ListOfDogs       { get; set; }
        public bool IsItTrue                        { get; set; }
    }
}

Controller class
using System.Linq;
using System.Web.Mvc;
using Web.Helper.TuplesHelper;
using Web.Model.TuplesViewModel;

namespace Web.UI.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var tupleValue = new MyDogList();

            var model = new TuplesViewModel
            {
                TestString  = tupleValue.TestString,
                ListOfDogs  = tupleValue.DogList().Where(x=>x.Contains("German Shepherd")),
                IsItTrue    = tupleValue.ItsTrue
            };
            return View(model);
        }
    }
}

Returning Multiple Values Using Tuples In C# Example

As you can see in the code examples above, I have an IEnumerable string that contains my list of dogs, I also have a test string and bool each returning values.

In the controller, you will see I have created a new view model and I'm populating the values of the model with my tuple values and also filtering the list to display only 'German Shepherd' before passing the view model to the view.

The code for the view is below:

View Code
@model Web.Model.TuplesViewModel.TuplesViewModel
@{
    ViewBag.Title = "Home Page";
}

<p>@Model.TestString</p>
<ul>
    @foreach (var data in Model.ListOfDogs)
    {
        <li>@data</li>
    }
</ul>
<p>It is @Model.IsItTrue</p

If we now run the code, you can see that the homepage now shows the return values that we have entered, this example uses hard-coded values, but we could have just as easily returned the data from a database or XML file.

Results for test code

If you found this example helpful, please leave a comment below.


Blog Form

 Please complete the required fields (*required)

 *
*