C # create an instance of a derived class in a base class

I have the following setup:

public abstract class A { public void f() { //Want to make an instance of B or C here //A bOrC = new ? } public abstract void f2(); } public class B : A { public override void f2(){} } public class C : A { public override void f2(){} } 

Is it possible? If so, how?

Edit: bOrC must be the type of a specific derived class f() called from

+7
source share
3 answers

I can think of two ways to solve this problem. One uses generics, and the other just requires an abstract method. Simple at first.

 public abstract class A { public void f() { A bOrC = newInstance(); } public abstract void f2(); protected abstract A newInstance(); } public class B : A { public override void f2(){} public override A newInstance(){ return new B(); } } public class C : A { public override void f2(){} public override A newInstance(){ return new C(); } } 

And now with generics

 public abstract class A<T> where T : A, new() { public void f() { A bOrC = new T(); } public abstract void f2(); } public class B : A<B> { public override void f2(){} } public class C : A<C> { public override void f2(){} } 
+8
source

You can use Activator.CreateInstance(this.GetType());

+4
source

This is impossible, and it can lead to some strange consequences. However, there is light work around rendering code that is easy to read.

 public abstract class A { public void f() { //Want to make an instance of B or C here //A bOrC = new ? A bOrC = Create(); } public abstract void f2(); public abstract A Create(); } public class B : A { public override void f2(){} public override A Create() { return new B(); } } public class C : A { public override void f2(){} public override A Create() { return new C(); } } 
0
source

All Articles