Simply doing modelType.ToString() isn't sufficient, How can i use it via Activator.CreateInstance?

Posted by programmerist on Stack Overflow See other posts from Stack Overflow or by programmerist
Published on 2010-04-17T07:21:05Z Indexed on 2010/04/17 7:23 UTC
Read the original article Hit count: 298

  public class MyController
    {
        public object CreateByEnum(DataModelType modeltype)
        {
            string enumText = modeltype.ToString(); // will return for example "Company"
            Type classType = Type.GetType(enumText); // the Type for Company class
            object t = Activator.CreateInstance(classType); // create an instance of Company class
            return t;
        }
    }

    public class CompanyView
    {
        public static List<Personel> GetPersonel()
        {
            MyController controller = new MyController();
            _Company company = controller.CreateByEnum(DataModelType.Company) as _Company;
            return company.GetPersonel();
        }
    }

    public enum DataModelType
    {
        xyz,
        klm,
        tucyz,
        Company
    }

Yes, I agree Activator.CreateInstance() is very useful. Unfortunately, I need to pass in the correct type. That means building the correct string to pass to Type.GetType(). If I trace through the call to Controller.CreatebyEnum() in the code I posted above, simply doing modelType.ToString() isn't sufficient, even for the case of DataModelType.Company. My solution'll be maintenance bottleneck. What would be better is something that takes the results of modelType.ToString() and then recursively searches through all the types found in all the assemblies loaded in the current AppDomain. According to MSDN, Type.GetType() only searches the current calling assembly, and mscorlib.dll. How can i do that? . i need best performance?

© Stack Overflow or respective owner

Related posts about c#3.0

Related posts about .NET