Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Christopher Bennage

Our WPF book is now available!


42m is not a constant

Here's a little CLR tidbit I picked up today while writing a [RowTest] with MbUnit.

If you want to specify a decimal value in C#, you add the suffix m or M.  You can read all about it here.  This means you might have something in your code  like this:

decimal myBigMoney = 19.95m;

Well, it turns out that 19.95m is not a constant value, it's actually shorthand that the compiler translates to

decimal myBigMoney = new decimal(19.95);

and "decimal" is an alias of the struct System.Decimal. This means that you can't pass the value 19.95m as an argument into an attribute, like this:

[RowTest(19.95m)]

(because attribute arguments must be constants!) Luckily, MbUnit 2.4 will implicitly convert your doubles into decimals for you...

Where credit is due: I discovered this here.



Comments

Kalpesh said:

Pardon my ignorance. But, can't it be defined as a constant at class level & be supplied to rowtest?
# October 31, 2007 5:24 PM

Christopher Bennage said:

Actually, it can't. Consider a class level member:

const decimal  myConstantDecimal = 3.14m;

Now, if I pass that into an attribute like so:

[Row(myConstantDecimal)]

The compiler still says:

"An attribute argument must be a constant expression, typeof expression or array creation expression"

# November 2, 2007 12:27 PM

About Christopher Bennage

Christopher is a software developer and consultant at Blue Spire Consulting, a company he co-founded with Rob Eisenberg in 2006. He is a Christian, a marginal musician, and an armchair philosopher. His interests include programming, liberal education, science, truth, beauty, and a number of deceased British authors (C. S. Lewis, G. K. Chesterton, and most recently Owen Barfield.) He lives in Tallahassee, FL with his wife and three children and still prefers to play as the Night Elves in WarCraft 3. Check out Devlicio.us!

Our Sponsors

Red-Gate!