2

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

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Try the Array.ConvertAll method.

Comments

-1

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.