Friday, April 30, 2021

C# Typecast checked and unchecked



using System;

namespace Console_Typecast
{
    class Program
    {
        static void Main(string[] args)
        {
            byte mybyte;
            int intValue = 257;
            mybyte = (byte)intValue; //Case 1
            //mybyte = checked((byte)intValue); //Case2
            //mybyte = unchecked( (byte) intValue);//Case 3
            Console.WriteLine(mybyte);
        }
    }
}

OUTPUT Case1 will be 1
OUTPUT Case2 will be System.OverflowException as shown below:




OUTPUT Case3 will be 1

NOTE:
We can change the default setting for overflow checking). To do this, we should modify the properties for the project by right-clicking on it in the Solution Explorer window and selecting the Properties
option. Click Build on the left side of the window to bring up the Build settings. Click the Advanced button.

Tick the Check the arithmetic overflow



Example2
Only compatible data types can be cast into another type.
using System;

namespace Console_Typecast
{
    class Program
    {
        static void Main(string[] args)
        {

            //Cannot convert bool to string
            bool result = 2 > 1;
            string mytrue = (string)result;
            Console.WriteLine(mytrue);

            //Cannot convert string to bool
            string state ="True"
            bool truth = (bool)state;
        }
    }
}






No comments:

Post a Comment

Hot Topics