invoke an instance of a class by its type

I am trying to write a generic method that will accept any type and create its instance so that I can use it later:

Example of a class that I want to dynamically generate:

public class bb_ColorScaleCriteriaTypes
    {
        public Dictionary<string, int> Types { get; set; }
        public bb_ColorScaleCriteriaTypes()
        {
            this.Types = new Dictionary<string, int>()
            {
                {"LowestValue", 1},
                {"Number", 0},
                {"Percent", 3},
                {"Formula", 4},
                {"Percentile", 5},
                {"HighestValue", 2},
                {"AutomaticMax", 7},
                {"AutomaticMin", 6},
                {"None", -1}
            };
        }

        public static int byName(string name)
        {
            if (name == null)
            {
                throw new ArgumentException("name");
            }
            int intValue = new bb_ColorScaleCriteriaTypes().Types[name];
            return intValue;
        }
    }

Normally I have another class that I can call like this:

public class bb_ColorScaleCriteriaTypesUI : DSDropDownBase
    {
        private const string NO_FAMILY_TYPES = "No types were found.";
        public bb_ColorScaleCriteriaTypesUI() : base("Color Scale Criteria Type") { }

        // Get Data Class that holds dictionary
        public static bb_ColorScaleCriteriaTypes cscTypes = new bb_ColorScaleCriteriaTypes();

        protected override SelectionState PopulateItemsCore(string currentSelection)
        {
            Items.Clear();

            Dictionary<string, int> d = new Dictionary<string, int>(cscTypes.Types);
        }

As you can see I am instantiating a class of bb_ColorScaleCriteriaTypes and then calling Types on it. However, I want to write a more generic implementation where I could just do something similar to this:

    public abstract class bb_ColorScaleCriteriaTypesUI : DSDropDownBase
    {
        public bb_ColorScaleCriteriaTypesUI (string name, Type elementType) : base(name) { this.ElementType = elementType; PopulateItems(); }

        private const string noTypes = "No Types available.";
        public Type ElementType;

        // how to instantiate an instance of ElementType here? 

        protected override SelectionState PopulateItemsCore(string currentSelection)
        {
            if (this.ElementType != null)
            {
            Dictionary<string, int> d = new Dictionary<string, int>(myTypeInstance.Types); //so I can call it here
        }

Looks like this got a little out of hand in the comments really quick.

Anyways, I don't mind using the Activator.CreateInstance() but how can I create an instance of type and cast it back to the type so its not a generic object?

Answers


Activator.CreateInstance() as the others have said. The return type is not a generic object, its the actual type you requested, its just returned as an object because that's the base class of everything.

If you want to do it "the right way", you'd define an interface or base class that all your classes derive / implement from and have the common methods that you need to call generically defined in the interface / base class. Then you can either use Activator.CreateInstance() or the factory pattern to new up the objects and return them as the interface / base class.


Need Your Help

Using django-photologue to assign single image to a model

python django postgresql photo photologue

I'm working on my first project in django, and the first part of it is a blog app. I've installed django-photologue which seems very useful for the intended purposes for later apps. Although this app

Autocomplete, tab-complete email input using AngularJS and Bootstrap

angularjs twitter-bootstrap email twitter-bootstrap-3

I need to create some sort of a function for an input that can auto complete and tab-complete when a user enters in a letter. It needs to consistently call the service to get all the emails relevan...