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

后端 未结 4 842
谎友^
谎友^ 2021-02-01 11:58

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 effec

4条回答
  •  庸人自扰
    2021-02-01 12:14

    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).

提交回复
热议问题