Looking to cast an Object to a known type at runtime. I have a class (call it Item for ease) which is the base class for Box. Box has it’s own properties as well as the ones from Item (obviously).
Basically I create an instance of Box using the CreateInstance method, this creates an Object of type object but the true type (as witnessed when doing ‘typeof’) is of type Box. I need to cast this Object back to Box without hard coding any switch / if etc. The code I have to test this is below and I’m running out of ideas.
//Base Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Test11
{
public class Item
{
public int property1 { get; set; }
public int property2 { get; set; }
public int property3 { get; set; }
public Item()
{
property1 = 1;
property2 = 2;
property3 = 3;
}
}
//Box Class - Inherits from Item
namespace Test11
{
public class Box : Item
{
public int property4 { get; set; }
public Box()
{
property4 = 4;
}
}
}
//Application Class
namespace Test11
{
class Program
{
static void Main(string[] args)
{
List<Item> BaseList = new List<Item>();
object obj = Assembly.GetExecutingAssembly().CreateInstance("Test11.Box");
Type t = Type.GetType("Test11.Box");
//The following line does not work, need to make it work :)
//BaseList.Add(obj as t);
Console.WriteLine(t.ToString());
Console.ReadLine();
}
}
}
I’ve tried many different ways now, the one featured above is one of many. Any ideas or help out there?
Your
BaseListis expectingItemobjects. You have to cast:Or: