-
Notifications
You must be signed in to change notification settings - Fork 0
Code in Depth
Sandesh Kota edited this page Mar 4, 2019
·
20 revisions
- Date Airthmatic
static DateTime IncrementByYear(DateTime d)
{
return new DateTime(d.Year + , d.Month, d.Day);
}
This code throws an exception on Feb 29, 2012. As it is not a valid date.
This issue caused much of Azure to Crash in Feb 2012
// Right Way
var newDate = date.AddYears(1);
- Overload Puzzle
private string Test(Int64 item) { return "Int64"; }
private string Test(Int32 item) { return "Int32"; }
private string Test(Object item) { return "Object"; }
Int16 itemInt16 = 42;
Int16 itemInt32 = 42;
Int16 itemInt64 = 42;
DateTime itemDate = new DateTime(2006, 03, 25);
Test(itemInt32)
Test(itemInt64)
Test(itemdate)
Test(itemInt16) => 32
// When a specific overload is not available, "closest match" is determined.
// Implicit Conversion and Explicit Compiler behavior is more ! than inheritance in fining the closest match
// So Int16's closest match Int32 is called
- Operations
Single one = 1;
Single three = 3;
Single x = one / three;
Double result = 3 * x ;
result == ?
Answers?
== 1.0, < 1.0, > 1.0
Math.Round(result, 7) == 1
What if? Single result = 3 * x ;
Reason: Base2 airthmatic
- Example 2
Double x = .1;
Double result = 10 * x ;
Double result2 = x + x + x + x + x + x + x + x + x + x;
result == result2 ?
Console.WriteLine( "{0} - {1}" , result, result2)
Console.WriteLine( "{0:R} - {1:R}" , result, result2)
Reason: Can't be held exactly in Base 2 system so there is a rounding error
- Division
Int maxDiscountPercent = 30;
Int markupPercent = 20;
Int niceFactor = 30;
Double discount = maxDiscountPercent * ( markupPercent / niceFactor) ;
discount ?
== 0
Reason: Integer division in C# truncates the value to nearest integer. So 20 / 30 becomes Zero
Error Code:
Int x = 9, int y = 10; int z = 100;
decimal interim = x / y;
Decimal result = z / interim ;
- Divide By Zero
Int zero = 0;
Int three = 3;
Int result = 3 / 0;
// Int, Decimal => Throws exception
// Single / Double => They can hold Infinity (Double.PositiveInfinity , Double.NegativeInfinity)
- Rounding
Math.Round(3.5); ==> 4
Math.Round(4.5); ==> 4
Reason: .Net rounds mid-point number to the nearest Even digit -> Banker's rounding
Math.Round(4.5, MidpointRounding.AwayFromZero); ==> 5
- Top Of Type
Int top = int.MaxValue;
Int next = top + 1;
// Int => Airthmatic overflow is not turned ON by default => Value rolls over to minimum value
// Decimal => overflow exception
// Single, Double => Infinity is supported => top + 1 is same as top.
- Single [Base2-32bit] , Double [Base2-64bit] & Decimal [Base10-128bit]
- Use "fuzzy" comparisons for Single & Double Data Types
- Base 10 & Base 2 rounds differently
- Avoid data Conversions between fractional type
- Decimal performance is 10 times slower than Single & Double
- Decimal for money, Double for everything else