Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hii
can anyone plz tell me how to activate all classes inherited from base class dynamically same time.
i create dynamic class using codedom..but now when i execute my software i have to write code for that class..(activation line)
e.g
C#
Frames.Add(new Business_Layer.SSN());
Frames.Add(new Business_Layer.ZipCode());
Frames.Add(new Business_Layer.First_Name());

if i created a dynamic class with a name phone..how can i dynamically add that line below above coded lines..
Posted
Updated 17-Jul-11 5:41am
v2
Comments
ely_bob 14-Jul-11 17:48pm    
Are you talking about code injection? or a component based creation approach?

1 solution

You should consider using dependency injection, such as MEF or Unity. But for something very simple and dirty you could do as follows:

C#
namespace Business_Layer
{
    using System;
    class SSN
    {
        public SSN()
        {
            Console.WriteLine(GetType().Name);
        }
    }
    class ZipCode
    {
        public ZipCode()
        {
            Console.WriteLine(GetType().Name);
        }
    }
    class First_Name
    {
        public First_Name()
        {
            Console.WriteLine(GetType().Name);
        }
    }
    class Phone
    {
        public Phone()
        {
            Console.WriteLine(GetType().Name);
        }
    }
}
namespace ConsoleApplication2
{
    using System;
    using System.Linq;
    using System.Reflection;
    class Program
    {
        static void Main(string[] args)
        {
            var myTypes =  Assembly.GetExecutingAssembly().GetTypes().Where(x => x.Namespace == "Business_Layer");
            foreach (var type in myTypes)
            {
                Frames.Add(Activator.CreateInstance(type));
            }
        }
    }
}


Output:


SSN<br />
ZipCode<br />
First_Name<br />
Phone<br />
Press any key to continue . . .
 
Share this answer
 
v2

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