Derived instance in base class

class baseClass { derivedClass nm = new derivedClass(); } class derivedClass : baseClass { } 

This code builds fine. What is the possible reason that C # will allow the creation of derivedClass objects in baseClass . Can you come up with any specific reasons for this?

+4
source share
4 answers

This code builds fine.

Yes - why do you think this is not so?

What could be a possible reason that C # allows you to create objects of a derived class in baseClass.

Because there is no reason to ban it?

Can you come up with any specific reasons for this?

Static factory methods, for example?

 // BaseClass gets to decide which concrete class to return public static BaseClass GetInstance() { return new DerivedClass(); } 

This is a really fairly common pattern. We often use it in Noda Time , where CalendarSystem is an open abstract class, but all concrete derived classes are internal.

Of course, crazy to have the exact example you specified - with an instance field that initializes itself by instantiating the derived class because it would explode the stack due to recursion - but this is not a question of being a derived class. You will get the same by initializing the same class:

 class Bang { // Recursively call constructor until the stack overflows. Bang bang = new Bang(); } 
+12
source

The developer I worked with created this code in our code base. I personally agree to its usefulness.

 public class Foo { public static Foo MagicalFooValue { get { return Bar.Instance; } } private class Bar : Foo { //Implemented as a private singleton } } 
+1
source

One obvious case is the factory method in the base class, returning the appropriate implementations based on some condition.

0
source

derivedClass can be created in baseClass because it is an accessible class. There is no reason C # should limit you to this. Similarly, you can create an instance of baseClass inside the baseClass itself.

0
source

All Articles