C
C#4mo ago
br4kejet

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
333fred4mo 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
br4kejet
br4kejetOP4mo 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
333fred4mo ago
I'm not sure what you mean there. Of course that works, you're providing all the type arguments
br4kejet
br4kejetOP4mo ago
I mean when I remove the generic parameter from CreateFailedResult and make it return OperationResult<string>, ReadString compiles fine
333fred
333fred4mo 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"
br4kejet
br4kejetOP4mo ago
That sucks
Want results from more Discord servers?
Add your server