MichaelTaylor3D
MichaelTaylor3D

Reputation: 1665

Can you pass a type and enforce what type is passed in C#?

I set up a method to pass a type as a parameter

private void SomeMethod(System.Type type)
    {
        //some stuff
    }

Is there a way to enforce the type so that you can only pass in types that inherit from a specific base class?

Upvotes: 4

Views: 88

Answers (2)

nneonneo
nneonneo

Reputation: 179412

Try making your function generic, and passing the type parameter in through the generic type parameter:

private void SomeMethod<T>() where T : U {
    Type type = typeof(T);
    // some stuff
}

You can use any type constraint listed here.

If it has to handle arbitrary type objects (e.g. when you don't have control over who calls the function), then you probably just have to use runtime assertions:

private void SomeMethod(System.Type type)
{
    if(!typeof(U).IsAssignableFrom(type)) {
        throw new ArgumentException("type must extend U!");
}

See also this question on Type Restriction.

Upvotes: 8

TheHe
TheHe

Reputation: 2972

there are a lot of possibilities...

instance-based:

private void SomeMethod(object list) // total generic

becomes

private void SomeMethod(IEnumerable<object> list) // enumerable-generic

or

private void SomeMethod(List<object> list) // explicit list

OR with generic functions:

private void SomeMethod<T>() where T : MyType // << contraints
{
    var theType = typeof(T);
}

call that:

var xyz = SomeClass.SomeMethod<string>(); // for example

for more info about constraints: http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.80).aspx

Upvotes: 3

Related Questions