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 .
I think you misunderstood
uncheckedblock. It only checks when simply an expression which results in a overflow or underflow.In your case you're calling
Convert.ToBytemethod. That method can throw whatever exception it wants. That has no relation withuncheckedblock.Your example is not valid
byte myInt = 300;won't compile. Try this, It won't throw exception, because we use expressions.Also note that
uncheckedis default in c#, so you don't need to explicitly sayuncheckedTo make it more clear let's create our own method
So what you expect here?
OverflowExceptionto be thrown or CLR should eat your exception?