Custom Class Converting in c#

873 views Asked by At

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..

2

There are 2 answers

0
Alexei Levenkov On BEST ANSWER

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.
10
Dave Zych On

You can't cast to a variable - you have to explicitly state the type. You'll need to check for each class separately:

if(mylist[i] is FirstType)
{
    //do something
}
else if (mylist[i] is SecondType)
{
    //do something
}
//etc

A possibly better alternative would be to create 4 separate lists using List<T> and hold each type separately:

var firstList = new List<FirstType>();
var secondList = new List<SecondType>();
//etc

Or, if possible, create a base class if the data is similar enough and use a List<T>.

public class MyBase
{
    public int Id { get; set; }
}

public class FirstType : MyBase
{
}

public class SecondType : MyBase
{
}

var list = new List<MyBase>();
list.Add(new FirstType());
list.Add(new SecondType());

As mentioned in the comments, you can use partial classes to do this as well. They allow you to define a class in 2 or more files. For example, see how the Profile class you posted is defined as public partial class Profile : ProfileBase? You can create your own file and define it again, with other interface implementations. For instance:

public interface IMyInterface
{
    public int Id { get; set; }
}

public partial class Profile : IMyInterface
{
    public int Id { get; set; }
}

This is a good overview on partial classes: http://msdn.microsoft.com/en-us/library/wa80x488.aspx