Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specified cast is not valid - List of double to list of float

So I store a list of float in a JSON file, this is what the JSON list looks like:

"RollSize": "[17.5,18.0,19.0,23.5,26.5,35.0,35.5,38.0]"

I use a method which returns a list of objects as there are multiple lists to return. I then cast the list of objects to a float. However the Specified cast is not valid receive an exception when doing this. But if I cast the list of objects to a double it works. Here is the two methods:

private void DisplayCutOffs(object sender, EventArgs e) {
            try {
// Errors here unless I cast to double 
                _view.CurrentCutOffValues = _systemVariablesManager.ReturnListBoxValues("CutOff").Cast<float>().ToList();
            }
            catch (Exception ex) {
                LogErrorToView(this, new ErrorEventArgs(ex.Message));
            }
        }

Repository method:

 public List<object> ReturnListBoxValues(string propertyName) {
            if (File.Exists(expectedFilePath)) {
                var currentJsonInFile = JObject.Parse(File.ReadAllText(expectedFilePath));
                return JsonConvert.DeserializeObject<List<object>>(currentJsonInFile["SystemVariables"][propertyName].ToString());
            }
            else {
                throw new Exception("Setup file not located. Please run the Inital Set up application. Please ask Andrew for more information.");
            }
        }

However I noticed that if I looped around the list in a foreach I could cast each value to a float. So I'm not sure what's going on here.

Anyone know?

like image 906
Andrew Avatar asked Oct 24 '25 18:10

Andrew


1 Answers

It sounds like you're cast is casting from object to (the type), where (the type) is either float or double. This is an unboxing operation, and must be done to the right type. The value, as object, knows what it is - and this exception is thrown if you unbox it incorrectly (caveat: there is a little wriggle room if you unbox it to something the same size and compatible - for example you can unbox an int-enum to an int and v.v.).

Options:

  • stick with object, but know what the data is and unbox it correctly - perhaps casting after the unbox, i.e. float f = (float)(double)obj; (the (double) here is the unbox from object to double; the (float) is the type conversion from double to float)
  • test the object type / use Convert.ToSingle
  • change the property to be a defined type in the first place, rather than object

Full examples:

List<object> actuallyDoubles = new List<object>{ 1.0, 2.0, 3.0 };
List<double> doubleDirect = actuallyDoubles.ConvertAll(x => (double)x); // works
// List<float> floatDirect = actuallyDoubles.ConvertAll(x => (float)x); // fails per question
List<float> floatViaDouble = actuallyDoubles.ConvertAll(x => (float)(double)x); // works
List<float> floatViaConvert = actuallyDoubles.ConvertAll(x => Convert.ToSingle(x)); // works
like image 172
Marc Gravell Avatar answered Oct 26 '25 09:10

Marc Gravell