0

I've been trying to make this simple method work:

public static object[] IsVow(object[] a)
{
    return a.Select(x =>
    {
        char test = (char)x;
        return "aeiou".Contains(test) ? test : x;
    }).ToArray();
}

Where a is an object[] of ints (like { 97, 99, 101 }, where it should return { 'a', 99, 'e' }).

However, it fails at char test = (char)x, printing System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Char', even though replacing (char)x with something like (char)97 works fine.

I coded two test methods to figure out what the problem was, and the fact that it's an object array seems to break it:

public static object[] objtest(object[] a)
{
    return a.Select(x =>
    {
        char test = (char)x;
        Console.WriteLine(test);
        return (object)(int)test;
    }).ToArray();
}

public static int[] inttest(int[] a)
{
    return a.Select(x =>
    {
        char test = (char)x;
        Console.WriteLine(test);
        return (int)test;
    }).ToArray();
}

Using the same array, inttest() works perfectly, but objtest() breaks at the same spot, even though they basically do the same thing. I'm not sure what causes this, I was under the impression that object allowed you to store any value of any type within it.

maromalo
  • 77
  • 6
  • 1
    Try char test = (char)(x as int). I haven’t tested this, and it might not work as I don’t know if you can cast object to int. The real question is why you are using a int[] as input. – SupaMaggie70 b Dec 01 '22 at 23:36
  • If you clarify what made you think that "object allowed you to store any value of any type within it." means "you can cast any type to any other type" there maybe some additional explanations, otherwise I think duplicates I selected explain what you should be doing and why casting boxed int to char fails. – Alexei Levenkov Dec 01 '22 at 23:37
  • 1
    When you _unbox_ a boxed value type instance, you must unbox it to exactly the right type. If you say `object boxed =1`, then `char c = (char)boxed;` will fail. As @SupaMaggie70b points out, you need an extra step `char c = (char)(int)boxed;` – Flydog57 Dec 01 '22 at 23:54

0 Answers0