Saturday, April 7, 2012

M magic for decimal creation

This will not work:

decimal decimalFromValue = 1.234;

 
 

I've been hacking around the problem like this:

double doubleFromValue = 1.234;
decimal decimalFromCasting = (decimal)doubleFromValue;

 
 

But hey, look at this:

[TestMethod]
public void TestMethod()
{
   decimal decimalFromValue = 1.234M;
   double doubleFromValue = 1.234;
   decimal decimalFromCasting = (decimal)doubleFromValue;
   Assert.AreEqual(decimalFromValue, decimalFromCasting);
}

 
 

This test compiles and passes! The M is the magic. I found this on page 22 of C# 4.0 in a Nutshell.

No comments:

Post a Comment