Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

derived instance in base class

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?

like image 211
Deepak Raj Avatar asked Dec 11 '22 17:12

Deepak Raj


2 Answers

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();
}
like image 98
Jon Skeet Avatar answered Dec 14 '22 06:12

Jon Skeet


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
    }
}
like image 20
Aron Avatar answered Dec 14 '22 07:12

Aron