Sometimes the C# compiler can do some type inference when you have to specify the generic parameters of some methods, like:
list.Select<[type of x.xx]>(x => x.xx)
Can be shorten as
list.Select(x => x.xx)
. This feature is quite unstable and confusing. Consider another example:
public interface ISome
{
int Method(string arg);
}
public class Mock<T>
{
public void Setup<TResult>(Func<T, TResult> func) { }
}
public static class It
{
public static T IsAny<T>() { return default(T); }
}
And we wish we can write this:
var mockSome = new Mock<ISome>();
mockSome.Setup(s => s.Method(It.IsAny()));
But C# compiler will raise error in this case:
The type arguments for method 'It.IsAny()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Since the type signature of ISome.Method
is consistant, it's known at compile time. But the C# compiler asks you to specify the generic parameter of It.IsAny
.
So we have to do this:
mockSome.Setup(s => s.Method(It.IsAny<string>()));
This is quite strange. Is there a way to formally, or, correctly and totally describe the C# compilers' type inference rule? (like, in what circumstances will C# compiler infer the type; in what circumstances won't?
IsAny()
was inferred. Perhaps StackOverflow would be more appropriate than CS -- there are more C# experts there. $\endgroup$ – chi Nov 26 '17 at 20:48