c# - Array of inherited from generic types -


code demonstrate problem:

static void main(string[] args) {     var = new a();     var b = new b();     base<>[] = new base<>[] { a, b }; // doesn't work }  class base<t> {     public string caption { { return typeof(t).tostring(); } } }  class : base<a> { } class b : base<b> { } 

perhaps went wrong direction. idea move caption base class (base become generic). non-generic version works without problems:

var = new base[] { a, b }; // no problems long base not generic 

there's no type<?> in c# - always have specify concrete generic type.

the way around make base<t> inherit non-generic base-class, or implement non-generic interface. use type of array.

edit:

in case extremely simple, since part of interface want doesn't include generic type argument. can either:

public abstract class superbase {   public abstract string caption { get; } }  public class base<t>: superbase {   public override string caption { { return typeof(t).name; } } } 

or, using interface:

public interface ibase {   string caption { get; } }  public class base<t>: ibase {   public string caption { { return typeof(t).name; } } } 

your array superbase[] or ibase[], respectivelly. in both cases, can see i'm not providing an implementation - both declarations "abstract", in sense.

in general, i'm trying keep non-generic stuff in non-generic base class, rather stuffing in derived generic classes. feels more clean :)


Comments