.NET 4.7 returning tuples and nullable values

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 great. So, with .NET 4.7, we have a new Tuple value type. So if I convert it it will be:

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);
        }
    }
}

      

Fine! Also, it won't work. The new value type of the tuple is not nullable, so it doesn't even compile.

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

+4


source to share


1 answer


By adding a nullable operator, ?

you can make the return type of the function GetResults()

nullable:

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

      

Your code will not compile because it is async

not allowed in a function Main()

. (Just call another function in Main()

instead)




Edit : Since the advent of C # 7.1 (just a few months after this answer was originally posted), async Main

methods are allowed .

+6


source







All Articles