Question

I have an app which pull the ARGB values of background color from a Isolated storage setting; where I have given the values in int datatype. however the color.fromargb() requires byte datatype but when i cast it, it gives an exception "invalid cast"

here is the exception code:

backcolor.Color = Color.FromArgb((byte)dailyspring_settings["back_color_a"],(byte)dailyspring_settings["back_color_r"], (byte)dailyspring_settings["back_color_g"], (byte)dailyspring_settings["back_color_b"]);

the isolated storage code

dailyspring_settings.Add("back_color_a",100 );
dailyspring_settings.Add("back_color_r",103 );
dailyspring_settings.Add("back_color_g",158 );
dailyspring_settings.Add("back_color_b",236);
Was it helpful?

Solution

As Ulugbek Umirov pointed out, the fix is to "double cast".

Imagine that s represents the expression dailyspring_settings["back_color_b"] such that the type of the expression is typed as object, and the object that it evaluates to is an int (System.Int32).

Thus to first go from object->int is done with the following Type Cast. A Type Cast changes the type of the expression or "view" of the object, but it does not change or create a new object - as such it will fail with an InvalidCastException if s does not evaluate to a int (System.Int32) value.

int i = (int)s;

Now, having an expression typed int, the next step is int->byte. This is done with a Type Conversion defined between an expression and a byte. The result is a new value, the byte.

byte b = (byte)i;

So, as suggested, putting it all together:

(byte)(int)dailyspring_settings["back_color_a"]

The above usages of "Type Cast" and "Type Conversion" are to illustrate a point; see the following questions for technical details and terminology.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top