rediVider
rediVider

Reputation: 1307

Pass a list of types, limiting the types to classes derived from a particular parent, in c#

I have a method on an object oriented database that creates tables based on their type.

I want to be able to send a list of types to get created, but i'm hoping to limit them to only classes derived from a specific base class (MyBase).

Is there a way i can require this in the method signature? Instead of

CreateTables(IList<Type> tables)

Can i do something that would

CreateTables(IList<TypeWithBaseTypeMyBase> tables)

I know i could check the base class of each type sent over, but if possible i'd like this verified at compile time.

Any suggestions?

Upvotes: 0

Views: 94

Answers (3)

dcp
dcp

Reputation: 55449

Why not just change the signature to:

CreateTables(IList<BaseType> tables)

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245449

You could do the following:

CreateTables(IList<MyBase> tables)
{
    // GetType will still return the original (child) type.
    foreach(var item in tables)
    {
        var thisType = item.GetType();
        // continue processing
    }
}

Upvotes: 1

recursive
recursive

Reputation: 86124

Have you tried this?

CreateTables(IList<MyBase> tables) 

I think that's all you have to do.

Upvotes: 0

Related Questions