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 with a name Widgetthat subclasses Bucket:

public class Widget : Bucket {  }

I want to do this:

Widget w = Controller.Dispense('widget');

I think this is possible given that a Widgetis Bucket. I could use the return type Dispense(string)for input Widget, but I would rather do it without a cast. Is there a way to smooth types Bucketand Widget?

+5
source share
3 answers

You can get some of what you are 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");
    }
 }
+3
source

- dynamic, , :

dynamic w = Controller.Dispense('widget');
+2

You can use the implicit conversion operator . This is defined in the class Bucketas follows:

public static implicit operator Widget(Bucket bucket)
{
    // return the typecast Widget (can also perform any conversion logic here if necessary)
    return (Widget)bucket;
}

Now you can perform the β€œimplicit” throw as if:

Bucket b = new Bucket();
Widget w = b;

Note use with caution in accordance with the pst comment, as well as from the MSDN link:

Conversion operators can be explicit or implicit. Implicit conversion operators are easier to use, but explicit operators are useful when you want operator users to know that a conversion is occurring.

+1
source

All Articles