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?

  • 1
    $\begingroup$ A priori a question about C# seems off-topic here. For C++, type inference is probably described in the standard, but I'm not sure whether there are equivalent whitepapers for C#. $\endgroup$ Nov 26 '17 at 16:08
  • 1
    $\begingroup$ I put it here because it's related to type system, and it's varies in languages. Anyway thanks for your answer. $\endgroup$
    – ice1000
    Nov 26 '17 at 16:28
  • 2
    $\begingroup$ Apparently there is a public spec: microsoft.com/en-us/download/details.aspx?id=7029. It should contain the type inference algorithm (see for example stackoverflow.com/questions/3697252/…). $\endgroup$ Nov 26 '17 at 17:04
  • $\begingroup$ This seems to be C# specific, though. I tried the equivalent in Scala, and the type argument to 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.