class baseClass
{
derivedClass nm = new derivedClass();
}
class derivedClass : baseClass
{
}
This code builds fine. What might be the possible reason for C# to allow creating derivedClass
objects in baseClass
. Can you think of any specific reasons for doing this?
This code builds fine.
Yes - why do you think it wouldn't?
What might be the possible reason for C# to allow creating derivedClass objects in baseClass.
Because there's no reason to prohibit it?
Can you think of any specific reasons for doing this?
Static factory methods, for example?
// BaseClass gets to decide which concrete class to return
public static BaseClass GetInstance()
{
return new DerivedClass();
}
That's actually a pretty common pattern. We use it a lot in Noda Time for example, where CalendarSystem
is a public abstract class, but all the concrete derived classes are internal.
Sure, it's crazy to have the exact example you've given - with an instance field initializing itself by creating an instance of a derived class - because it would blow up the stack due to recursion - but that's not a matter of it being a derived class. You'd get the same thing by initializing the same class:
class Bang
{
// Recursively call constructor until the stack overflows.
Bang bang = new Bang();
}
A developer I used to work with produced this code in our codebase. I personally agree its useful.
public class Foo
{
public static Foo MagicalFooValue
{
get { return Bar.Instance; }
}
private class Bar : Foo
{
//Implemented as a private singleton
}
}
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