Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 490
Alexander Hartvig Nielsen Avatar asked May 01 '26 04:05

Alexander Hartvig Nielsen


2 Answers

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;
like image 181
dav_i Avatar answered May 04 '26 03:05

dav_i


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?

like image 24
Luaan Avatar answered May 04 '26 05:05

Luaan