This and That

Dear Future Jamie:

DI with a private constructor

When you are doing DI with a private constructor, this syntax will not work:

            String animalTypeName = ConfigurationManager.AppSettings["animalTypeName"].ToString();
            Type animalType = Type.GetType(animalTypeName);
            IAnimal animal = (IAnimal)Activator.CreateInstance(animalType);

Instead use this syntax:

            String animalTypeName = ConfigurationManager.AppSettings["animalTypeName"].ToString();
            Type animalType = Type.GetType(animalTypeName);
            IAnimal animal = (IAnimal)FormatterServices.GetUninitializedObject(animalType);

Params Keyword

When you have a series of overloaded methods that are taking on an ever-growing number of parameters, consider using the params keyword.  For example, instead of this:

        public void NameMe(String FirstName)
        {

        }

        public void NameMe(String FirstName, String LastName)
        {

        }

        public void NameMe(String FirstName, String MiddleName, String LastName)
        {

        }

Do this:

        public void NameMe(params String[] parameters)
        {

        }

Love Current Jamie

One Response to This and That

  1. Rob Seder says:

    Jamie,

    With the use of the “params” keyword, Framework Design Guidelines might disagree slightly. They say that params should be used in cases when you would otherwise pass in an array. So, if you have a function that was going to take in an array of names (String[] names) – then you can consider using params.

    However, if you have different, discrete arguments like firstName, middleName, lastName, then you wouldn’t because inside of your method – how would you handle that? What do you do if the only pass in two names? What if they pass in 103 names?

    So, I think the params keyword is really just supposed to be use to handle n-number of items that are of the same time, and of the same use. FWIW

    -Rob

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: