Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of Decimal.One, Decimal.Zero, Decimal.MinusOne in .Net

Simple question - why does the Decimal type define these constants? Why bother?

I'm looking for a reason why this is defined by the language, not possible uses or effects on the compiler. Why put this in there in the first place? The compiler can just as easily in-line 0m as it could Decimal.Zero, so I'm not buying it as a compiler shortcut.

like image 497
Jasmine Avatar asked Apr 13 '09 22:04

Jasmine


People also ask

What is Decimal zero c#?

Zero is a C# Decimal field that represents the number zero (0).

Is Decimal 0?

The decimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9; the decimal separator is the dot "." in many countries (mostly English-speaking), and a comma "," in other countries.


1 Answers

Small clarification. They are actually static readonly values and not constants. That has a distinct difference in .Net because constant values are inlined by the various compilers and hence it's impossible to track their usage in a compiled assembly. Static readonly values however are not copied but instead referenced. This is advantageous to your question because it means the use of them can be analyzed.

If you use reflector and dig through the BCL, you'll notice that MinusOne and Zero are only used with in the VB runtime. It exists primarily to serve conversions between Decimal and Boolean values. Why MinusOne is used coincidentally came up on a separate thread just today (link)

Oddly enough, if you look at the Decimal.One value you'll notice it's used nowhere.

As to why they are explicitly defined ... I doubt there is a hard and fast reason. There appears to be no specific performance and only a bit of a convenience measure that can be attributed to their existence. My guess is that they were added by someone during the development of the BCL for their convenience and just never removed.

EDIT

Dug into the const issue a bit more after a comment by @Paleta. The C# definition of Decimal.One uses the const modifier however it is emitted as a static readonly at the IL level. The C# compiler uses a couple of tricks to make this value virtually indistinguishable from a const (inlines literals for example). This would show up in a language which recognize this trick (VB.Net recognizes this but F# does not).

like image 119
JaredPar Avatar answered Oct 12 '22 08:10

JaredPar