helloooo,
Actually, i want to know something. please read this code...

using System;
using System.Collections.Generic;
using System.Text;

namespace temp
{
    class Program
    {
     
        static void Main(string[] args)
        {
Int16 i = Int16.MaxValue;
            
Console.WriteLine("Simple: " + (i ));
unchecked
{
Console.WriteLine("Unchecked: " + (i + 1));
}
checked
{
try
{
Console.WriteLine(i + 1);
        }
    
catch (Exception ee)
{
Console.WriteLine("Error in Checked Block");
}
}
}
    }
}

this code not give any exception. please any body tell me why? But if i use Int32 then it will generate exception.
Thank's in advance....

nick.crane commented: Good question +1

Recommended Answers

All 3 Replies

A very good question.
I tried the code (in VS2005) and get the same results.
It is because the compiler is using an Int32 for the result of the calculation.
Constants are Int32 by default and the result is therefore being promoted to Int32.
Try this instead. It gives the result you expected.

Int16 i = Int16.MaxValue;

Console.WriteLine("Simple: " + (i));
unchecked
{
    Console.WriteLine("Unchecked: " + (++i));
}
checked
{
    i = Int16.MaxValue;
    try
    {
        Console.WriteLine(++i);
    }

    catch (Exception ee)
    {
        Console.WriteLine("Error in Checked Block");
    }
}

Thank you... for your help.
i try this code it it working also.

using System;
using System.Collections.Generic;
using System.Text;

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

            Int16 x = Int16.MaxValue;
            try
            {
                Int16 sum=checked((short)(x+1));
            }
                catch(OverflowException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }

But issue is why fist method not working. please tell in detail. pleaseeee..
how int16 converted in int32 automatically.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.