views:

176

answers:

3

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?

+1  A: 

Try the Array.ConvertAll method.

Silver Phoenix
-1 for not explaining how to use Array.ConvertAll
PP
+5  A: 

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.

Jon Skeet
+1: This is my favorite question during an interview. People usually get confused between CONVERT and CAST
A9S6
A: 

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; }

Lalit
-1 for using Convert.ToString when there's no such package Convert
PP