Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# create instance of the derived class in the base class

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

like image 509
Clivest Avatar asked Feb 27 '11 19:02

Clivest


People also ask

What C is used for?

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 ...

Is C or C++ same?

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.

What is the full name of C in C?

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++”.

Is C language easy?

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.


2 Answers

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(){}
}
like image 122
unholysampler Avatar answered Sep 29 '22 14:09

unholysampler


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

like image 27
Ken Wayne VanderLinde Avatar answered Sep 29 '22 15:09

Ken Wayne VanderLinde