The C# language should infer a method's generic type argument from return type if the type argument is only used for return value #9203
-
Transferred from the following issue: dotnet/roslyn#77474 Current SituationThe following code yields compiler error using System;
using System.IO;
using System.Text.Json;
namespace ClassLibrary1
{
public class Options
{
private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions() { IgnoreReadOnlyProperties = true, WriteIndented = true };
public static Options Load()
{ using FileStream fs = new FileStream("", FileMode.Open, FileAccess.Read, FileShare.Read);
return JsonSerializer.Deserialize(fs, _jsonOptions) ?? throw new InvalidOperationException("Cannot deserialize application configuration file. Invalid format.");
}
}
} This is due to the fact that the C# language currently doesn't infer a type argument from the expected return value. Desired SituationThe above return JsonSerializer.Deserialize<Options>(fs, _jsonOptions); If a method's generic parameter type is solely used for the method's return value, wouldn't it make sense then to use the expected return type to inference then for this generic parameter? There'd be no other source for inference otherwise. If the expected return type wasn't the one to be created by the method, a generic parameter type argument could still be provided. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
See: #92 |
Beta Was this translation helpful? Give feedback.
See: #92