Advertisement
RabbitB

Conversion Comparisons

Jul 3rd, 2014
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.42 KB | None | 0 0
  1. // Original Design
  2.  
  3. Volume gallonsLeft = Volume.Gallons(1.0f);
  4. gallonsLeft += 1.0f;                        // 2 gallons
  5. gallonsLeft += Volume.Ounces(64.0f);                // 2.5 gallons
  6. Volume litersLeft = gallonsLeft.inLiters;           // 9.46 liters
  7.  
  8. MethodThatExpectsFloat(gallonsLeft);                // Gets 2.5 gallons
  9. MethodThatExpectsLiters(litersLeft);                // Gets 9.46 liters
  10.  
  11. // Suggested Design
  12.  
  13. Volume volumeLeft = 1f * Volume.Gallon;
  14. volumeLeft += 1f * Volume.Gallon;       // 2 gallons
  15. volumeLeft += 64f * Volume.Ounce;       // 2.5 gallons
  16. volumeLeft -= 500f * Volume.Milliliter;     // 2.37 gallons
  17.  
  18. float gallonsLeft = volumeLeft / Volume.Gallon;
  19. float litersLeft = volumeLeft / Volume.Liter;
  20.  
  21. MethodThatExpectsFloat(gallonsLeft);        // 2.37 gallons
  22. MethodThatExpectsFloat(litersLeft);     // 8.97143 liters
  23.  
  24. // Hybrid Design
  25.  
  26. Volume gallonsLeft = 1f * Volume.Gallon;    // Volume.Gallon keeps gallons as its 'native' unit; this is inherited by gallonsLeft. The actual stored value is still in the common unit, liters.
  27. gallonsLeft += 1f;              // 2 gallons
  28. gallonsLeft += 64f * Volume.Ounce;      // 2.5 gallons
  29. gallonsLeft -= 500f * Volume.Milliliter     // 2.37 gallons
  30. Volume dramsLeft = gallonsLeft.inDrams      // 'Native' unit is drams, as there's an explicit instead of implicit conversion here.
  31.  
  32. MethodThatExpectsFloat(gallonsLeft);        // Gets 2.37
  33. MethodThatExpectsFloat(dramsLeft);      // Gets 2424.74; internally both gallonsLeft and dramsLeft store the same value: 8.96 (liters).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement