XSharpPublic icon indicating copy to clipboard operation
XSharpPublic copied to clipboard

Invalid cast exception with assignment from usual (int) to Nullable<float>

Open hpetriffer opened this issue 3 months ago • 3 comments

The assignment from an usual of type int to 'float?' results to an InvalidCastException. If the usual is a float it works without problems.

	local x := 1 as usual
	local y := 1 as float?

	y := x

XSharpTests.zip

hpetriffer avatar Sep 17 '25 06:09 hpetriffer

Hansjoerg, The problem here is that the USUAL contains a LONG value. The compiler generates this code:

		__Usual x;
		x = 1;
		__Float? y;
		y = 1;
		y = (__Float?)__Usual.ToObject(x);

__Usual.ToObject(x) returns a long in this case.

If you write the code as y := (FLOAT) x

then it works, because the compiler generates code that converts the usual to a float and then assigns that to the nullable float. I am not sure if there is a simple solution to this. This fails too

	local x := 1.0 as usual
	local y := 1 as long?
	y :=  x

We will probably have to add some logic to the compiler to change assignments for

Nullable<T> := usual

to

Nullable<T> := (T) usual

RobertvanderHulst avatar Sep 17 '25 13:09 RobertvanderHulst

At the moment we are using the workarround y := (FLOAT) x, but I think it is important to have a solution for this. Unfortunally we have always a mix between usual types and strong types in code.

hpetriffer avatar Sep 17 '25 13:09 hpetriffer

I will see what I can do

RobertvanderHulst avatar Sep 17 '25 14:09 RobertvanderHulst