TheGeekery

The Usual Tech Ramblings

C# Bashing Me on the Head

This is a stupid one that had me baffled today. I am writing a weather app for my Windows Mobile phone1. I was defining some custom classes to handle the various different portions of the weather. For example, temperature can be readable in Celsius, or Fahrenheit. So I built a custom class to handle both. I was stumbling on a weird issue of type conversion when I didn’t think there should be one.

The temperature class was relatively simple, doing the basic math required to convert Celsius to Fahrenheit, and back again. I figured the same would be the case for pressure as well, after all, it is a simple multiplication converting millibars to inches.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Pressure
{
    private float _mb;
    private float _in;
    public float millibars
    {
        get
        {
            return _mb;
        }
        set
        {
            _mb = value;
            _in = value * 0.0295301;
        }
    }
    public float inches
    {
        get
        {
            return _in;
        }
        set
        {
            _in = value;
            _mb = value * 33.8637526;
        }
    }
}

When attempting to compile this, I was being thrown the following error:

Cannot implicitly convert type ‘double’ to ‘float’. An explicit conversion exists (are you missing a cast?) (CS0266)

Unsure of where the conversions were being done, I was scratching my head. Then it struck me. Just typing a decimal numbers to do the conversions get treated as doubles. So the 0.0295301 and 33.8637526 where both being treated as doubles, and the error was actually regarding value not being explicitly converted to match. Fortunately, this is easily remedied with a single letter, forcing C# to type the number from double to float.

Lines 14, and 27 became the following:

start:14
1
            _in = value * 0.0295301f;
start:27
1
            _mb = value * 33.8637526f;

Notice the f after the numeric? That forces C# to treat it as a float, rather than a double. Then the error goes away.

Now back to continuing to build an application to consume the Weather Underground’s API.


  1. Yes I know there are lots already floating around, but it’s an exercise I wanted to try

Comments