Blogroll Me!

Lives in India/Chennai/Chennai, speaks English.
This is my blogchalk:
India, Chennai, Chennai, English.

A blog on what is happening in the .NET world in India.  

Anand's .NET WebLog


Home Archives Contact

Tuesday, June 24, 2003 :::
Division by Zero:::  

There was a post in the CNUG forums that a/0 in C# resulted in a DivisionByZero Exception while in VB resulted in a value Infinity.

Well the code in VB(Option Explicit off) and C# is as follows:

VB Code
Dim a As Integer
b = a / 0
Console.WriteLine(b)

C# Code
int a,b;
b=a/0;

The output of the VB code will be Infinity while that of the C# code will be a DivisionByZero exception. The question was why this difference.

This nothing to do with the VB or the C# compiler, but rather the way VB is. Inifinity is not a value defined by VB, but rather by the CLR. But the catch is, Infinity is a float/Double value.

In VB, as the "/" operator always does float division, values are converted to double and a double is returned, which is stored in b. So VB does not raise an exception but rather returns a value Infinity. If the variable b is defined as an integer in the above code, there will be a overflow exception as the returned value is a float and that will not fit into a int. If you tried the above with the VB integer division operator(\) the you would get the same error.

In C# as both the operand are integers, an integer division happens and the exception is raised. If both the variables are defined as float, then the C# code will also return the value Infinity.




::: posted by Anand at 3:53 PM

Comments: Post a Comment

 
Subscribe to Anand's .NET WebLog!


powered by Bloglet


Listed on Blogwise Listed on BlogShares Technorati Profile

Powered by Blogger