vote up 1 vote down star
1

This is my function.

public Dictionary<string, string> ArrayToDictionaryConverter(object [] objArray)
    {
        string[] strArray = new string[objArray.Length];
        strArray =(string[])objArray;
        Dictionary<string, string> dictionary = null;
        try
        {
            dictionary = new Dictionary<string, string>();
            for (int iVal = 0; iVal < strArray.Length; )
            {
                dictionary.Add(strArray[iVal], strArray[iVal + 1]);
                iVal += 2;
            }
        }
        catch (Exception ex)
        {
        }
        return dictionary;
    }

Getting error :

Unable to cast object of type 'System.Object[]' to type 'System.String[]'.

Why ? is this wrong convention / Casting?

flag

64% accept rate

3 Answers

vote up 2 vote down check

Try the Array.ConvertAll method.

link|flag
vote up 4 vote down

You can't cast an expression to a particular type if it's not actually of that type, or a compatible one (or there's an explicit conversion).

In this case, the array wasn't a string[] - it was an object[]. It could have been a string[], which is why the compiler allowed you to write the cast in the first place - but at execution time the CLR found that it was just an object[].

Do you expect every element in the array to already be a string? If so, you should just cast each element individually. If not, you'll have to add a call to ToString (or some other way of converting each element to a string) - but be careful of null values.

As an aside, empty catch blocks are a really bad idea. What do you really want to happen if something goes wrong? And what kind of errors do you want to handle in what way? Some errors to think about:

  • What if one of the keys is null?
  • What if you get duplicate keys?
  • What if the input array has an odd number of elements?

Finally, I'd suggest putting the i += 2 in the for loop "header" instead of at the end of the block.

link|flag
+1: This is my favorite question during an interview. People usually get confused between CONVERT and CAST – A9S6 Dec 31 at 8:56
vote up 0 vote down

See This is working: public Dictionary ArrayToDictionaryConverter(object [] objArray) { string[] strArray = Array.ConvertAll(objArray,Convert.ToString);
Dictionary dictionary = null; try { dictionary = new Dictionary(); for (int iVal = 0; iVal < strArray.Length; ) { dictionary.Add(strArray[iVal], strArray[iVal + 1]); iVal += 2; } } catch (Exception ex) { } return dictionary; }

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.