3

Given a type declared as shown below

public class EqualityProbe<T>
{
  public EqualityProbe( Func<T> functionToGetActualValue, T expectedValue, string probeDescription) {..}

Client code:

// cannot infer bool here
new EqualityProbe(CanConnectToMachine, true, "Probe machine is online")
// compiles fine
new EqualityProbe<bool>(CanConnectToMachine, true, "Probe machine is online")

My understanding is that type-inference doesn't work for method groups (e.g. CanConnectToMachine) or anonymous methods (lambda expressions).
But in this case, why doesn't the compiler infer the type argument from the second argument

Gishu
  • 134,492
  • 47
  • 225
  • 308
  • possible duplicate of [Why can't the C# constructor infer type?](http://stackoverflow.com/questions/3570167/why-cant-the-c-constructor-infer-type) – AakashM Apr 20 '11 at 06:47
  • possible duplicate of [Why doesn't C# support implied generic types on class constructors?](http://stackoverflow.com/questions/45604/why-doesnt-c-sharp-support-implied-generic-types-on-class-constructors) – nawfal May 27 '13 at 03:28

2 Answers2

2

C# doesn't support type inference on constructors, although this can often be overcome through the use of a factory class.

See the answer here: Why can't the C# constructor infer type?

Community
  • 1
  • 1
Iridium
  • 23,323
  • 6
  • 52
  • 74
1

Well, that how C# is ! It doenst infer for constructors. While instantiating a generic type, you need to specify the Type(s) that will be used for the generic ones.

Dipti Mehta
  • 537
  • 3
  • 13