I have the following set up:
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 this possible? If so how?
Edit: bOrC
needs to be the type of the particular derived class f()
is called from
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
While C and C++ may sound similar, their features and usage differ. C is a procedural programming language that support objects and classes. On the other hand C++ is an enhanced version of C programming with object-oriented programming support.
Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'. So ++ being the increment operator, C has an incremented version called as “C++”.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
I can think of two ways to solve this issue. One uses generics and the other just requires an abstract method. First the simple one.
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(){}
}
You can use Activator.CreateInstance(this.GetType());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With