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.
It sounds like
this.Opacity
is a double value, and the compiler doesn't like you trying to cram a decimal value into it.Since
Opacity
is a double value, I would just use a double from the outset and not cast at all, but be sure to use a double when dividing so you don't loose any precisionYour 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:
That
(double)
has to be explicitly stated in C#, but can be implied by VB's more 'forgiving' compiler.In my opinion, it is desirable to be as explicit as possible. This adds clarity to the code and aids your fellow programmers who may eventually read it.
In addition to (or instead of) appending a
.0
to the number, you can usedecimal.ToDouble()
.Here are some examples:
You should use
5000.0
instead of5000
.