Dryadwoods
Dryadwoods

Reputation: 2929

Enforce Type variable to be of a specific base class type

Having the following code:

class Car{}
class WV : Car{}
class BMW: Car{}
class Bike{}
class Yamaha : Bike {}
class KTM : Bike{}

void DoSomething(<some other parameters>, Type targetType){}

//I call DoSomething with:
service.DoSomething(...., typeof(BMW));

Is there any way to enforce the targetype to be only for the base class Car while the programmer is writing the code?

During the execution is easy to check, but I want to enforce the expected base class that we want.

I want that when the programmer types: service.DoSomething(...., typeof(KTM)); the code gives an error on compile.

Thanks

Upvotes: 0

Views: 34

Answers (1)

Oleksii Aza
Oleksii Aza

Reputation: 5398

You could try using generics for your use case. It would look like:

void DoSomething<T>(<some other parameters>) where T: Car {}

service.DoSomething<BMW>(...);

Upvotes: 1

Related Questions