GetType and typeof – how to get rid of overloads

The other day I needed a method for a piece of framework code handling different kinds of incoming parameters.

Since I don’t know what types the incomming parameters have I had to use some reflection and the operator typeof() and the GetType() method. If you haven’t used those methods before, here’s a small how to guide.

Using typeof()

The typeof() operator returns a System.Type and for example to get the value of a string the statement looks like this:

System.Type type = typeof(string);

The typeof operator is to be used for type checks at compile time, try and use it on anythign other than a namespace or a type and you will get a compilation error. Even though this is an operator it is not possible to overload it.

Using GetType()

The GetType() method is what you want to use for checking types during runtime. This method will also return a System.Type, and it’s used like this:

System.Type type = myObject.GetType();

A small example

My example code creates a container class that has a Dictionary with string keys and string values. The data coming in can be of the types string, double, int, decimal and bool.

Before adding the data to the Dictionary, a conversion is made, using culture info to change the formatting of the result string.

The Container class

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication
{
   internal class Container
   {
      Dictionary<string, string> collection = new Dictionary<string,string>();

      // Adds a parameter pair to the Dictionary.
      // If the parameter key already exists, it will remove the existing one and replace it.
      public void AddParameter(string keyName, object keyValue)
      {
         if (this.collection.ContainsKey(keyName))
         {
            this.collection.Remove(keyName);
         }

         Type type = keyValue.GetType();
         if (type.Equals(typeof(string)))
         {
            this.collection.Add(keyName, (string)keyValue);
         }
         else if (type.Equals(typeof(double)))
         {
            this.collection.Add(keyName, TypeConverter.DoubleToString((double)keyValue));
         }
         else if (type.Equals(typeof(int)))
         {
            this.collection.Add(keyName, TypeConverter.IntToString((int)keyValue));
         }
         else if (type.Equals(typeof(decimal)))
         {
            this.collection.Add(keyName, TypeConverter.DecimalToString((decimal)keyValue));
         }
         else if (type.Equals(typeof(bool)))
         {
            this.collection.Add(keyName, TypeConverter.BoolToString((bool)keyValue));
         }
      }

      public override string ToString()
      {
         StringBuilder result = new StringBuilder();
         foreach(var pair in collection)
         {
            result.Append("Key: " + pair.Key + "t" + " Value: " + pair.Value + "n");
         }
         return result.ToString();
      }
   }
}

The TypeConverter class

using System.Globalization;

namespace ConsoleApplication
{
   internal class TypeConverter
   {
      public static string DoubleToString(double value)
      {
         return value.ToString(CultureInfo.InvariantCulture);
      }

      public static string IntToString(int value)
      {
         return value.ToString(CultureInfo.InvariantCulture);
      }

      public static string DecimalToString(decimal value)
      {
         return value.ToString(CultureInfo.InvariantCulture);
      }

      public static string BoolToString(bool value)
      {
         return value.ToString();
      }
   }
}

The Program

using System;

namespace ConsoleApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         Container container = new Container();

         container.AddParameter("int", (int)5);
         container.AddParameter("double",  (double) 55555555555.55555555555555555555555);
         container.AddParameter("decimal", (decimal)55555555555.55555555555555555555555m);
         container.AddParameter("bool", (bool)true);

         Console.WriteLine(container.ToString());
         Console.ReadKey();
      }
   }
}

Happy coding!

C# Generic method – without Generics
Tagged on:     

5 thoughts on “C# Generic method – without Generics

  • May 10, 2011 at 23:28
    Permalink

    Hmm, I know it’s an example of reflection but wouldn’t it be easier to just overload the AddParameter method ?

    Mani 🙂

    Reply
    • May 11, 2011 at 00:16
      Permalink

      😮

      But, but, but, I got rid of all my overloads and it’ so smooth!!
      Actually the incoming data was already boxed so I’d have to unbox it, felt easier to move it all down into my helper class.

      Nice to see you are alive 🙂

      Reply
  • May 11, 2011 at 09:53
    Permalink

    Nasty switch statements though !!!!!

    Reply
    • May 11, 2011 at 10:03
      Permalink

      Nah, perfect readability of that code 😉

      Reply
  • April 10, 2013 at 06:21
    Permalink

    Hmm it appears like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to the whole thing. Do you have any recommendations for beginner blog writers? I’d certainly appreciate it.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.