.NET 4.7 returning Tuples and nullable values
Asked Answered
H

1

21

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?

Headland answered 12/5, 2017 at 21:55 Comment(0)
R
33

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.

Rudelson answered 12/5, 2017 at 22:8 Comment(2)
How to call async methods from Main method: blogs.msdn.microsoft.com/benjaminperkins/2017/03/08/…Scuta
What about form an anonymous lambda?Woodworm

© 2022 - 2024 — McMap. All rights reserved.