Example 1:
if ((Value ?? 0d) <= 0d)
{
//some code
}
Example 2:
if ((Value ?? (double)0) <= (double)0)
{
//some code
}
What is the difference between these two? and which one is better to use?
According to the language specification, 0.0 is the same as 0.0d. JLS Section 3.10.2 describes this as follows: A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d.
%d displays using a fixed width to accommodate the largest possible value for the expression being displayed. %0d displays the minimum width, suppressing any leading 0's or spaced.
The double is a fundamental data type built into the compiler and used to define numeric variables holding numbers with decimal points. C, C++, C# and many other programming languages recognize the double as a type. A double type can represent fractional as well as whole values.
Both code snippets are equivalent, as the type-cast will be performed by the compiler at compile-time, and the result treated as a constant. Note that this is standard behaviour, not just a compiler optimization; otherwise, you would not be able to use casts for constants:
const double d1 = (double)0; // allowed
const double d2 = Math.Pow(2, 4); // error: "The expression being assigned to 'd2' must be constant"
Specifying the proper literal suffix is nonetheless preferred as it keeps your code concise. Another popular convention for specifying doubles is to append .0
:
if ((Value ?? 0.0) <= 0.0)
The first one is better.
Second one makes the cast happen at runtime. First one declares constant as double right away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With