开发者

Is there a zero [ 0 ] constant somewhere in any Microsoft .NET class?

I'm just curious and I know it's not of much value, but here it goes...

I think that I have seen something like that somewhere but I'm 开发者_开发知识库not sure.

I mean something like this:

var zero = Class.Zero;

I tried looking at the Math class but it's not there.

I also know that I can use an unsigned value type like ushort.Min to get a Zero ( 0 ) value; it's not what I'm asking here... :D


Do you mean default(T)?

int zero = default(int);

This represents the default value for a given type, for int this is 0. You should not use this if you know already you need zero though, only in the case that you have a type at run time for which you need the default value.


There's one for Decimal.Zero and a few other more complex types like TimeSpan.Zero, IntPtr.Zero and BigInteger.Zero. But for regular numeric types, just use 0.


The .Net Framework doesn't define constants for values like 0. If you want to use 0 just use 0

Defined numeric constants in the .Net Framework typically revolve around the limits of a given numeric type, values which hold special relevance or cases where the zero value requires special / complex initialization. For example

  • Int32.Max
  • Int32.Min
  • Double.NaN

The literal 0 doesn't fit these categories for most numeric types (Decimal being one exception)


Some immutable reference types have pre-defined instances for "empty" values. String, for example, defines String.Empty. This is done because a valid String--even one with no characters--must reference a valid heap object, but if there are a thousand empty String variables they may all refer to the same heap object. Unless an application doesn't happen to use any empty strings at all, creating one empty-string instance at application startup and allowing it to be shared among everyone who needs an empty string will be more efficient than creating a new empty string object every time one is needed.

No such benefit would exist with value types. Although there are some value-type constants declared (e.g. Math.Pi), their declaration is for convenience, not efficiency. Saying "myDouble = Math.Pi" is no more efficient than "MyDouble = 3.14159265358979323846264338327950288419716939937510#"--it's just easier to read and validate (would anyone looking at the above code notice if the first "328" were mistyped as "238")? If one wants a floating-point constant zero, the most natural and easiest-to-read notation would simply be 0#.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜