Search code examples
c#classgenericstypeconverter

Custom Class Converting in c#


I stuck converting class..

I have an arraylist that contains 4 different class which are not releated each other.

for example when user choose one like mylist[i], i should convert it, it's certain class and after can use .. i mean like

var type = mylist[i].GetType();

so now I have item's type. and when I create a variable as this type i mean like

var newItem = (type)mylist[i]

but type is not a class so then i cant convert it.

I am not sure if i am clear..


Solution

  • You can't cat to type defined at run time.

    Assuming types you have are similar, but not related you can

    • use dynamic to switch to late binding. It will allow you to call methods you want at cost of compile type safety. "Duck typing" sample can be found in Duck type testing with C# 4 for dynamic objects
    • dynamically create methods that will do what you want with types defined at runtime via reflection or expression.