I have a method that returns an object of type Bucket
:
Bucket Dispense(string typeName);
I have a class named Widget
that subclasses Bucket
:
public class Widget : Bucket { }
I want to do this:
Widget w = Controller.Dispense('widget');
Which I think should be possible, given that a Widget
is a Bucket
. I could cast the return type of Dispense(string)
to type Widget
, but I'd much rather do this without a cast. Is there a way of aliasing the Bucket
and Widget
types?
You could get some of what you're looking for using generics:
public class BucketDispenser
{
public TBucket Dispense<TBucket>(string typeName) where TBucket : Bucket
{
Bucket widget= new Widget();
// or
Bucket widget = new OtherWidget();
return (TBucket)(object)widget;
}
}
Then you can use it as follows:
public class MyClass
{
public MyClass()
{
var disp = new BucketDispenser();
Widget widget = disp.Dispense<Widget>("widget");
OtherWidget otherWidget = disp.Dispense<OtherWidget>("otherWidget");
}
}
Another simple option is you can use dynamic to avoid casting, it will bypass compile-time type checking:
dynamic w = Controller.Dispense('widget');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With