c# - Set no type for a static method in a generic class -


not fan of java, java allows not setting types generic classes , in case threats type object type. however, far know, c# enforces setting type of <t> anytime generic class has instantiated or speaking used. however, let's have generic class, , need static method in there not rely on type of <t>.

firstly, know can moved separate context or can set dummy type of <t>, programming puzzle there way call without defining type of t?

example:

 class test<t> t: itestable {      ...      public static void createtestfile(string filename) {...}  }  test.createtestfile("test.txt"); 

this can done java , apparently can't in c#. wanna make sure.

java , c# implement generics differently:

  • java uses type erasure, means @ compile time, put in <t> erased , becomes object. something<foo> , something<bar> same type @ runtime, , wil equal something<object>.

  • c# uses run-time reification, meaning each type use distinct t, runtime generates new class altogether, using open generic version template (which means generates underlying native code once per t call it). something<foo> , something<bar> 2 unrelated types far clr concerned.

hopefully understand why difference important scenario. ignoring t trivial in java, not easy in c#.

if don't need t in code, use non-generic method:

abstract class test {     public static void createtestfile(string filename) {...} }  class test<t> : test     t : itestable {      ... } 

here, that's better :)

also, note instance methods, can use covariant , contravariant interfaces loosen requirement known t @ compile-time. instance, if use covariant interface, need know base type of t.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -