C# Generic Type Inference With Multiple Types
My question is, why can't TInput be inferred in this situation?
It can - it's TResult
which can't be inferred, and there's no way of specifying "partial" inference.
What you can sometimes do is separate the type parameters into ones for a generic type and ones for a generic method, so you'd end up with:
// Explicitly state TResult, and infer TInput
Serializer<MySuperType>.Serialize(x);
Why not just write it like this:
public string SerialiseAs<TResult>(TResult input)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(TResult));
MemoryStream stream = new MemoryStream();
ser.WriteObject(stream, input);
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
Since TInput
derives from TResult
, you really don't need to specify at all.