0

I have two classes, one is abstract and the one that inherits it

public abstract class Monitor {

   public SmallMonitor MiniMonitor { get; set;}
   public abstract bool Execute();
}

public class ToolBox1000 : Monitor
{
    //implements Monitor
    public ToolBox1000()
    {
        SmallMonitor monitor = new SmallMonitor();
        monitor.Test = true;
        monitor.Number = 1230;
    }
}

public class ToolBox2000 : Monitor
{
   //implements Monitor
    public ToolBox2000()
    {
        SmallMonitor monitor = new SmallMonitor();
        monitor.Test = true;
        monitor.Number = 2034;
    }
}

My problem is that I need to get the list of all the classes that implement Monitor using reflection and then add them to a list i need to return..

public static IEnumerable<Monitor> Monitors
{
    get
    {
        List<Monitor> monitors = new List<Monitors>();
        List<Type> classes = GetClasses(typeof(Monitor)).OrderBy(x => x.Name).ToList();
        foreach(Type c in classes)
        {
            object oMonitor = Convert.ChangeType(c, typeof(Monitor)).GetType();
            Monitor mig = (Monitor)oMonitor;
            monitors.Add(mig);
        }
        return monitors;
    }
}

private static List<Type> GetClasses(Type baseType)
{
    return Assembly.GetCallingAssembly().GetTypes().Where(type => type.IsSubclassOf(baseType)).ToList();
}

The problem is that I am getting a invalid cast in this line

  object oMonitor = Convert.ChangeType(c, typeof(Monitor)).GetType();

and that I need to implement IConvertible

I am not sure how to accomplish this, i have tried several times with no luck, can this be done?

jedgard
  • 868
  • 3
  • 23
  • 41

1 Answers1

2

you are trying to convert a instance of class Type to an instance of the class Monitor which is not possible. from what I understand you are trying to create an instance of the type and add to the monitors list

based on some assumptions you may try the following code

    public static IEnumerable<Monitor> Monitors
    {
        get
        {
            List<Monitor> monitors = new List<Monitor>();
            List<Type> classes = GetClasses(typeof(Monitor)).OrderBy(x => x.Name).ToList();
            foreach (Type c in classes)
            {
                object oMonitor = Activator.CreateInstance(c);
                Monitor mig = (Monitor)oMonitor;
                monitors.Add(mig);
            }
            return monitors;
        }
    }

note the changed line object oMonitor = Activator.CreateInstance(c);

Activator.CreateInstance will create an instance of the given type given that it is not abstract and has a public parameter-less constructor.

pushpraj
  • 13,458
  • 3
  • 33
  • 50