.NET 4.7 returning Tuples and nullable values

Kelly picture Kelly · May 12, 2017 · Viewed 10.7k times · Source

Ok lets say I have this simple program in .NET 4.6:

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static async void Main()
        {
            var data = await Task.Run(() =>
            {
                try
                {
                    return GetResults();
                }
                catch
                {
                    return null;
                }
            });

            Console.WriteLine(data);
        }

        private static Tuple<int,int> GetResults()
        {
            return new Tuple<int,int>(1,1);
        }
    }
}

Works fine. So with .NET 4.7 we have the new Tuple value type. So if I convert this it becomes:

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static async void Main()
        {
            var data = await Task.Run(() =>
            {
                try
                {
                    return GetResults();
                }
                catch
                {
                    return null;
                }
            });

            Console.WriteLine(data);
        }

        private static (int,int) GetResults()
        {
            return (1, 2);
        }
    }
}

Great! Except it doesn't work. The new tuple value type is not nullable so this does not even compile.

Anyone find a nice pattern to deal with this situation where you want to pass a value type tuple back but the result could also be null?

Answer

adjan picture adjan · May 13, 2017

By adding the nullable type operator ? you can make the return type of the GetResults() function nullable:

private static (int,int)?  GetResults()
{
    return (1, 2);
}

Your code would not compile though because async is not allowed in the Main() function. (Just call another function in Main() instead)


Edit: Since the introduction of C# 7.1 (just a few months after this answer was originally posted), async Main methods are permitted.