While applying opacity to a form, should we use a decimal or a double value?
I want to use a track-bar to change a form's opacity.
This is my code:
decimal trans = trackBar1.Value / 5000;
this.Opacity = trans;
When I build the application, it gives the following error:
Cannot implicitly convert type 'decimal'
to 'double'
.
I tried using trans
and double
but then the control doesn't work. This code worked fine in a past VB.NET project.
An explicit cast to double like this isn't necessary:
double trans = (double) trackBar1.Value / 5000.0;
Identifying the constant as 5000.0
(or as 5000d
) is sufficient:
double trans = trackBar1.Value / 5000.0;
double trans = trackBar1.Value / 5000d;
A more generic answer for the generic question "Decimal vs Double?": Decimal for monetary calculations to preserve the precision, Double for scientific calculations that do not get affected by small differences. Since Double is a type which is native to the CPU (internal representation is stored in base 2), calculations made with Double perform better then Decimal (which is represented in base 10 internally).
Your code worked fine in VB.NET because it implicitly does any casts, while C# has both implicit and explicit ones.
In C# the conversion from decimal to double is explicit as you lose accuracy. For instance 1.1 can't be accurately expressed as a double, but can as a decimal (see "Floating point numbers - more inaccurate than you think" for the reason why).
In VB the conversion was added for you by the compiler:
decimal trans = trackBar1.Value / 5000m;
this.Opacity = (double) trans;
That (double)
has to be explicitly stated in C#, but can be implied by VB's more 'forgiving' compiler.