Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between 0d and (double)0?

Tags:

c#

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?

like image 742
hendryanw Avatar asked Jun 24 '14 05:06

hendryanw


People also ask

What does 0d mean in Java?

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.

What is the difference between %D and %0d?

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

What does double mean in C#?

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.


2 Answers

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)
like image 99
Douglas Avatar answered Nov 06 '22 21:11

Douglas


The first one is better.

Second one makes the cast happen at runtime. First one declares constant as double right away.

like image 44
MarcinJuraszek Avatar answered Nov 06 '22 20:11

MarcinJuraszek