Click here to Skip to main content
16,020,840 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
I have folder that contains some classes with the same behavior (they contain one Run function that get int param and all inherit from the same class).
I need to create in loop instance from these classes and execute their function with the parameter.
That is what I started-
C#
f = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "ConsoleApplication3.JJJ");
A[] a = new A[f.Count()];

for (int i = 0; i < a.Count(); a[i]=new A(), i++);
    for (int i = 0; i < a.Count(); i++)
        {
            // (a[i] as f[i].GetType()).Run(0);
        }


I don’t know how to continue, and if it's good at all…
Posted
Updated 26-Jan-14 0:38am
v2
Comments
Mitchell J. 26-Jan-14 6:37am    
Please clean your code sample. It's not legible.
Karthik_Mahalingam 26-Jan-14 6:47am    
post your full code..

No, if you create a new instance of class A, then you can't cast it to a derived type: that doesn't work. All you can do is cast a derived type to a type lower in teh inheritance chain, such as it's base type:
C#
public class A { }
public class AA : A { }
public class AB : A { }
public class AAA : AA { }
public class ABA : AB { }

You can cast an instance of AA or AB to A, or you can cast an instance of AAA to A or AA, and an instance of ABA to A or AB, but you can't cast an instance of A to any of the others, or of AAA to AB!

If you want to call the Run method for a derived class, then you need to create an instance of the derived class explicitly, not create an instance of the base class and try to "magically get" an instance of the derived class from that.
 
Share this answer
 
Comments
Rahul VB 26-Jan-14 13:01pm    
OG, ctrl + shift + d in opera i dont know about other browsers :laugh
You can use reflection if your classes are in an another assembly as here:
(I have created another library that contains classes, and used reflection over that library.)

C#
static void Main(string[] args)
{
    try
    {
        Assembly l = Assembly.LoadFile(@"d:\tmp\Test_ReflectionSampleLib.dll");
        var types = l.GetExportedTypes().ToList();
        var btype = types.First(t => t.Name == "Base");
        var dtypes = types.Where(t => t.BaseType == btype);
        int i = 0;
        foreach (var d in dtypes)
        {
            ConstructorInfo ci = d.GetConstructor(Type.EmptyTypes);
            MethodInfo mi = d.GetMethod("Foo");

            mi.Invoke(ci.Invoke(null), new object[] { i++ });
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900