3

I'm trying To make the method to return a Tuple of: Tuple<DateTime?, DateTime?>.

In case the code is being able to generate two DateTime types, I'm uses the Tuple.Create to create a return statement with:

public Tuple<DateTime?, DateTime?> GeTuple()
{
    if (something)
    {
        return Tuple.Create(startDate, endDate);
    }
    else
    {
        return Tuple.Create(null, null); //--> This line produce the error.
    }
}

but I'm getting this error of:

The type arguments for method 'Tuple.Create(T1, T2)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91

2 Answers2

5

The compiler can't look at Tuple.Create(null, null) and tell that you meant to create a Tuple<DateTime?, DateTime?>. The fact that it's then being returned from a method which returns a Tuple<DateTime?, DateTime?> doesn't matter: the compiler doesn't consider that.

Use one of these:

new Tuple<DateTime?, DateTime?>(null, null)

Tuple.Create((DateTime?)null, (DateTime?)null)
canton7
  • 37,633
  • 3
  • 64
  • 77
3

As a complementary answer of @canton7's answer, I just want to add that C# 7 introduced a new struct called ValueTuple that has explicit support by the compiler:

So your code can take advantage of it as follows :

public (DateTime?, DateTime?) GeTuple() => boolean-expression ? (startDate, endDate) : (default(DateTime?), default(DateTime?));

Note that (DateTime?, DateTime?) is just syntactic sugar for :

System.ValueTuple<DateTime?, DateTime?>.

This Stackoveflow question has answers that go deeper into the difference between the Tuple class and the ValueTuple struct and when to use what.

Zack ISSOIR
  • 964
  • 11
  • 24