wpearse
wpearse

Reputation: 2422

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?

Upvotes: 5

Views: 968

Answers (3)

cuongle
cuongle

Reputation: 75306

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

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

Upvotes: 2

armen.shimoon
armen.shimoon

Reputation: 6401

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");
    }
 }

Upvotes: 3

McGarnagle
McGarnagle

Reputation: 102763

You can use an implicit conversion operator. This is defined within the Bucket class as 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 cast "implicitly" as it were:

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

Note use with caution as per pst's comment, and also 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 users of the operator to be aware that a conversion is taking place.

Upvotes: 1

Related Questions