Type arguments cannot be inferred from usage

This is the code I have now:
public OperationResult<string> ReadString(string address) {
OperationResult<EfortData> read = this.ReadEfortData();
if (!read.IsSuccess)
return read.CreateFailedResult();
...
}
public OperationResult<string> ReadString(string address) {
OperationResult<EfortData> read = this.ReadEfortData();
if (!read.IsSuccess)
return read.CreateFailedResult();
...
}
And CreateFailedResult is implemented as:
public OperationResult<A1> CreateFailedResult<A1>() => new OperationResult<A1>(this.ErrorCode, this.Message);
public OperationResult<A1> CreateFailedResult<A1>() => new OperationResult<A1>(this.ErrorCode, this.Message);
I don't really understand why it can't figure out that A1 is going to be string, since that's the type argument for ReadString's return type?
6 Replies
333fred
333fred5mo ago
The return type of ReadString and the method you call there are entirely unrelated C# only does inference from arguments to a method. That's it
bighugemassive3
bighugemassive3OP5mo ago
Surely it should check the type arguments though? Because if I change CreateFailedResult to return OperationResult<string> and remove <A1> it works fine
333fred
333fred5mo ago
I'm not sure what you mean there. Of course that works, you're providing all the type arguments
bighugemassive3
bighugemassive3OP5mo ago
I mean when I remove the generic parameter from CreateFailedResult and make it return OperationResult<string>, ReadString compiles fine
333fred
333fred5mo ago
Again, of course it does. You're providing all the type information there As I said C# only infers type arguments based on parameters. CreateFailedResult has no parameters, therefore no type argument inference can happen There's no magical "oh, this local is used later in the function to return, therefore I'll go back and do inference"
bighugemassive3
bighugemassive3OP5mo ago
That sucks
Want results from more Discord servers?
Add your server