#1,063 – Explicit Conversions and Type Parameters

You can’t explicitly convert a type parameter to either a reference type or a value type.  Casts to reference or value types are disallowed at compile-time.  The compiler allows casting the type parameter to an interface type and this conversion will succeed at run-time if the object implements that interface.

        public class ThingContainer<T>
        {
            private T thing;

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

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

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

                // Will compile, but throw
                // InvalidCastException at run-time
                // if T doesn't implement IBark
                IBark ib = (IBark)t;
            }
        }

        static void Main(string[] args)
        {
            ThingContainer<Dog> dogcont = new ThingContainer<Dog>();
            dogcont.SetThing(new Dog("Bowser"));

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

            Console.ReadLine();
        }
Advertisement