Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

types

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?

like image 213
MichaelTaylor3D Avatar asked Sep 12 '25 10:09

MichaelTaylor3D


2 Answers

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.

like image 182
nneonneo Avatar answered Sep 14 '25 23:09

nneonneo


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

like image 38
TheHe Avatar answered Sep 14 '25 22:09

TheHe