Default null generic type

  • A+
Category:Languages

When i try to use prepare("", ""); I'm getting compile error why? I set default value null what is the point compiler now.I said if i didn't put any class put there null.

Error CS0411 The type arguments for method 'Program.prepare(string, string, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

class Program {     static void Main(string[] args)     {         var person = prepare("", "");     }      private static Person prepare<T>(string test, string Url, T postData = null)          where T : class     {         //if postdata null do somethnig (post data can be any class it is           //not person class)          //than return person     } }  class Person  {     public int age { get; set; }     public string name { get; set; } } 


The problem is that the compiler needs to know what type T is, even if you don´t provide it. Imagine you´re method would do anything with the provided parameter:

private static Person prepare<T>(string test, string Url, T postData = null)      where T : MyClass {     if(T != null) t.DoSomething();     return new Person(); } 

Now the compiler has to infer a type for T and thus you have to provide it - even if at runtime you provide null for the arg. That postData is actually null is a runtime-information, the compiler does not have this information - it looks solely on the types, not the actual values.

Apart from this it´s hard to suggest what you actually need. Depending on your actual code and what you´re doing with postData you may not even need generics at all.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: