-1

Is it possible to create a generic class<T> which the generic type T will be the base class of it?

i.e:

MyClass<Base1> b1 = new MyClass<Base1>();
MyClass<Base2> b2 = new MyClass<Base2>();

b1.Name="test";
b2.ID=1;

Base Classes:

class Base1
{
   protected string Name{ get; set;}
}

class Base2
{
   protected int ID{ get; set;}
}

Inherited Class:

class MyClass<T>:T //here is the question is it possible dynamic inheritence
{

}
eakgul
  • 3,658
  • 21
  • 33
  • 4
    The answer to `is it possible` is usually "why don't you try it yourself"? – Zohar Peled Jun 28 '16 at 09:56
  • no, but you can use composition instead – Aleksey L. Jun 28 '16 at 09:59
  • Of course I already tried before (: My purpose was adding a few property into a library classes which is not belong me. i.e: Adding UIAutomationID property into Button, Picker, Label, TextBox, but also I want to use their own properties. – eakgul Jun 28 '16 at 10:17

1 Answers1

0

It's possible to use a constraint on T thus forcing T to be of type baseclass, like this:

public class baseclass
{
    // base class code
}

// perfectly valid
public class derived1<T> : baseclass where T : baseclass
{
    // derived class code
}

It's impossible to compile the following code, since T is a type parameter, and the compiler must infer it from usage. obviously that can't be done like this.

public class derived2<T> : T
{
    // derived class code
}
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121