Arkadiusz Rycyk Arkadiusz Rycyk - 3 months ago 30
C# Question

.NET 3.5 Change object type at runtime

Is there an easy way of doing this in 3.5 ? I have found something called "dynamic" in .NET 4.0.

I have a class of UI which Inherits from CrestronControlSystem class. There I want to be able define
an unknown type of a Panel which would then be instantiated inside of a method.

I don't want to do Boxing/Unboxing because

a) everyone says it's bad

b) I have to cast object type inside of the ControlSystem where I define and use all my UIs. And at this point I would have to know what each UI is in order to cast it, and I don't want this.

so (XpanelForSmartGraphics)home.UIs[0].UI_IPID if it's an object type with XpanelForSmartGraphics via Boxing/Unboxing.

I have tried quite few things with Generics but can't get it to work the way I want it because Generics do not support Properties...

Code:

public class ControlSystem : CrestronControlSystem
{
..........
public Home home = new Home("Home", 1, 1); // this just defines my home object and takes number of rooms and number of UIs as a parameter
.........
home.UIs[0].DefineUI(0x03, "xpanel", "Study"); // here is where I want to say "this unknow object is now XpanelForSmartGraphics because string parameter = "xpanel"
.........
home.UIs[0].myPanel.BooleanInput[1].BoolValue = true; // here is how I want to use it, so no casting.
}

public class UI : CrestronControlSystem
{
public ?????? myPanel; // how would it be defined ?

.......
public void DefineUI(ushort id, string type, string location)
{
.........
myPanel = ?????? ; // how ? :)
.........
}
}


Thanks

edit



so this is kind of what I need but I want to be able to call members
of XpanelForSmartGraphics "normal way" thorugh dot operator. This still
behaves as object :

public void DefineUI(ushort id, string type, string location)
{
if (type == "xpanel")
{
Type panelType = typeof(XpanelForSmartGraphics);
this.myPanel = Activator.CreateInstance(panelType);
}
}


so I can't call it this way from ControlSystem class :

home.UIs[0].myPanel.BooleanInput[1].BoolValue = true;


where BooleanInput[1].BoolValue it's just a property of XpanelForSmartGraphics

Thanks

Answer

You can create instance dynamicaly with Activator class. The Activator.CreateInstance method need the Type of the created instance.

The Type can be provided by hardcoded way:

if (type == "xpanel") { return typeof(MyXPanel); }

Or you can provide type dynamicaly by Type.GetType method.

Your can can look like this:

public class UI : CrestronControlSystem {
    public object myPanel;

    public void DefineUI(ushort id, string type, string location) {
        Type panelType = Type.GetType(type);
        this.myPanel = Activator.CreateInstance(panelType);
    }
}