Guye Incognito
Guye Incognito

Reputation: 2844

Can you construct a different derived class based on a parameter passed?

I'm wondering if something like this is possible...

class Thing
{
        public Thing(int i)
        {
        }
}

class DerivedThing : Thing
{
        public DerivedThing(int i)
        {
        }
}

_thing = new Thing(0)

_derivedthing  = new Thing(1)

If you pass 0 you get a Thing, if you pass 1 you get a DerivedThing This is not complete, just an illustration.. But basically I'm wondering if/how you could return different derived classes based on the value of a parameter passed to the baseclass constructor? Or do you just need another bit of code which decides which constructor to call?

Upvotes: 2

Views: 104

Answers (3)

Jodrell
Jodrell

Reputation: 35716

No, and why do you want to?

You may as well type

var thing = new Thing();

var derivedThing = new DerivedThing();

You could something like,

public static class ThingFactory
{
    public interface IThing {}

    public enum ThingType
    {
        Thing,
        DerivedThing
    }

    public static IThing CreateThing(ThingType type)
    {
        switch(type)
        {
            case ThingType.DerivedThing:
                return new DerivedThing();

            default:
                return new Thing();
        }
    }

    private class Thing : IThing {}

    private class DerivedThing : Thing {}
}

Allowing,

var thing = ThingFactory.CreateThing(ThingType.Thing);

var derivedThing = ThingFactory.CreateThing(ThingType.DerivedThing);

Upvotes: 1

Dariusz
Dariusz

Reputation: 22271

To answer your question: no, it is not possible. But...

You are actually looking for a Factory pattern. You can easily add a distinguishing if/case in a factory method and still have a relatively clean code.

Factory pattern description

Upvotes: 7

SLaks
SLaks

Reputation: 887767

That is not possible.

Instead, you can make a static Thing Create(int i) method that decides which constructor to call.

Upvotes: 3

Related Questions