Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast object returned from method to subclass

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?

like image 687
wpearse Avatar asked Sep 12 '12 04:09

wpearse


2 Answers

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");
    }
 }
like image 169
armen.shimoon Avatar answered Sep 30 '22 05:09

armen.shimoon


Another simple option is you can use dynamic to avoid casting, it will bypass compile-time type checking:

dynamic w = Controller.Dispense('widget');
like image 39
cuongle Avatar answered Sep 30 '22 05:09

cuongle