#1,064 – Getting Around Inability to Explicitly Convert Type Parameters

You can’t explicitly convert a type parameter to either a value type or a reference type (you can convert to an interface).

To get around this restriction, you can use the as operator on the type parameter.  This gives you a way to effectively convert the type parameter, get the code to compile, and avoid runtime exceptions.

    class Program
    {
        public class ThingContainer<T>
        {
            private T thing;

            public void SetThing(T t)
            {
                thing = t;

                // Won't compile
                //int i = (int)t;

                // Do this instead
                int? i = t as int?;
                if (i.HasValue)
                    Console.WriteLine("Your int: " + i);

                // Won't compile
                //Dog d = (Dog)t;

                // Do this instead
                Dog d = t as Dog;
                if (d != null)
                    Console.WriteLine("Your Dog: " + d.Name);
            }
        }

        static void Main(string[] args)
        {
            ThingContainer<int> intcont = new ThingContainer<int>();
            intcont.SetThing(5);

            ThingContainer<Dog> dogcont = new ThingContainer<Dog>();
            dogcont.SetThing(new Dog("Bowser"));

            ThingContainer<Cow> cowcont = new ThingContainer<Cow>();
            cowcont.SetThing(new Cow("Bessie"));

            Console.ReadLine();
        }
    }

1064-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment