C# Casting a Class implementing interface to Class based on type

My question is best explained with an example:

public IPlotModel MyPlotModel;
public ??? CastedModel;

public Constructor()
{
    MyPlotModel = new PlotModel(); //This should be interchangable with other types
                                   //E.g.: MyPlotModel = new OtherModel();
    CastedModel = (MyPlotModel.GetType()) MyPlotModel;
}

This is basically what I want. CastedModel should be cast to the type that MyPlotModel is.

I've had some success using Convert.ChangeType(). I manage to change the type of CastedModel to the correct type, but I can't manage to change the value of CastedModel to MyPlotModel.

This is what I tried:

Convert.ChangeType(CastedModel, MyPlotModel.GetType());
CastedModel = MyPlotModel;

But MyPlotModel is still recognized as an interface even though it's initialized as a PlotModel.

Thanks in advance, Alexander.

Upvotes: 3

Views: 132

Answers (2)

Luaan
Luaan

Reputation: 63732

The tricky part is that you must know the correct type at compile-time - there's no other place where that would make sense. The only way to do this is to use generics, as @dav_i suggested.

Think about how the instantiation should work - is it something the wrapper class should handle (dav_i's code), or is it something that should be passed from the outside instead?

Are you really supposed to handle the exact type outside of the wrapper class? Remember, when using an interface, you shouldn't treat it differently based on the actual class implementing the interface (look up Liskov's substitution principle and other similar concepts in OOP).

You're really not explaining anything about the intent behind what you're doing. Where do you want to use the actual type? What's the point of the interface? What are you trying to hide, and what do you want to expose?

Upvotes: 1

dav_i
dav_i

Reputation: 28107

This seems like you should use a generic class:

public class Example<TPlotModel> where TPlotModel : IPlotModel, new()
{
    public TPlotModel PlotModel { get; private set; }

    public Example()
    {
        this.PlotModel = new TPlotModel();
    }
}

which you can then instantiate and use like

var myExample = new Example<MyPlotModel>();
MyPlotModel foo = myExample.PlotModel;

Upvotes: 9

Related Questions