Casting a generic type variable

1. What will happen if we specify generic type parameter by a value type and will cast it to a reference type object using as operator?

If we specify generic type parameter by a value type the result of expression is always null.

 

Example 1:

        private static void Convert<T>(T param)

        {           

            string obj = param as string;

            Trace.WriteLine(obj);

        }

 

        static void Main(string[] args)

        {

            //Result is null

            Convert(5);           

            Console.ReadKey();

        }

 

Example 2:

        private static void Convert<T>(T param) where T : struct

        {

            string obj = param as string;

        }

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s