c# - Generic Generics or Type argument inference and inheritance -


i trying generics in .net 4.5 c# , honestly, i'm not sure if possible or it's called. makes searching more difficult.

anyways, best explain example.

let's have interface:

public interface isomebase {} 

and example of implementation

public class anobject : isomebase {}  public class anotherobject : isomebase {} 

then i've got classa has few generic methods so

public class classa {     public t somemethod1<t>() t : class, isomebase     {         //do stuff , return t         return default(t);     }      public list<t> somemethod2<t>(expression<func<t,object>> someexpression ) t : class, isomebase     {         //do stuff , return list<t>         return new list<t>();     } 

}

i want able use (which can):

public class someimplementation {     public void test()     {         var obj = new classa();         var v = obj.somemethod1<anobject>();         var v2 = obj.somemethod2<anotherobject>((t) => t.tostring());     } } 

but want able use (this won't work due type argument required. understand t in classb different t in every method in class a:

public class classb<t> : classa t: isomebase {     public t tester()     {        //this not possible , requires me add type argument.           return somemethod1(); //i leave out type argument , have compiler infer          // of time want able apply same type methods on classa.          // , of time want able specify type arguments on per method basis     } } 

i want avoid having wrap classa this:

public class classa<t> : classa t : class, isomebase {     public t somemethod1()     {         return somemethod1<t>();     }      public list<t> somemethod2(expression<func<t, object>> someexpression)     {         return somemethod2<t>(someexpression);     } } 

i've been searching , reading on can hands on. nothing seems fit. perhaps i'm not searching using right terminology because, honestly, don't know it's called.

any or pointers appreciated.

you're not giving compiler enough information infer type argument should use.

type inference complex process go through but, in general if method type parameter doesn't appear in parameter list no type inference performed type parameter. might want read c# spec. understand details of type inference.

hopefully can further clarify it.


Popular posts from this blog