unchecked is not working

374 views Asked by At

I was just trying some of the samples question in c# and came through the follwing problem

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Class1
    {
        public static int Add(int a, int b)
        { return a + b; }
        static void Main(string[] args)
        {
            byte myByte = 200;
            byte myInt = 100;
            byte ans;
            unchecked
            {
                ans = Convert.ToByte(myByte + myInt);
            }
            Console.WriteLine("Value of myByte: {0}", myByte);
            Console.ReadLine();


        }
    }
}

In the above case even if the underflow/overflow happens inside unchecked block , its throwing an exception . Please help .

1

There are 1 answers

6
Sriram Sakthivel On BEST ANSWER

I think you misunderstood unchecked block. It only checks when simply an expression which results in a overflow or underflow.

In your case you're calling Convert.ToByte method. That method can throw whatever exception it wants. That has no relation with unchecked block.

Your example is not valid byte myInt = 300; won't compile. Try this, It won't throw exception, because we use expressions.

byte myByte = 0;
int myInt = 300;
unchecked
{
    myByte = (byte)(myInt + myByte);
}

Also note that unchecked is default in c#, so you don't need to explicitly say unchecked


To make it more clear let's create our own method

private static void DoSomething(int a, int b)
{
    throw new OverflowException();
}

unchecked
{
    DoSomething(1,2);
}

So what you expect here? OverflowException to be thrown or CLR should eat your exception?