C# Program to Demonstrate Exception Handling for Invalid TypeCasting in UnBoxing

«
»

This is a C# Program to illustrate exception handling for invalid typeCasting in unboxing.

Problem Description

This C# Program Illustrates Exception Handling for Invalid TypeCasting in UnBoxing.

Problem Solution

Here it demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.

Program/Source Code

Here is source code of the C# Program to Illustrate Exception Handling for Invalid TypeCasting in UnBoxing. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Illustrate Exception Handling for Invalid TypeCasting in UnBoxing
 */
class TestUnboxing
{
    static void Main()
    {
        int num = 123;
        object obj = num; 
        try
        {
            int j = (short)obj; 
            System.Console.WriteLine("Unboxing");
        }
        catch (System.InvalidCastException e)
        {
            System.Console.WriteLine("{0} Error: Incorrect unboxing", e.Message);
        }
        System.Console.Read();
    }
}
Program Explanation

This C# program is used to illustrate exception handling for invalid TypeCasting in UnBoxing. Demonstrate a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Runtime Test Cases
 
Specified Cast is not Valid.Error : Incorrect Boxing

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.