Friday 14 January 2011

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

Was trying to interpret data returned to my WCF service from the client and encountered some type conversion issues:



// Within this Hashtable, against a given key, i would recieve from the client either a
// single string (note: not a string array with one entry) OR a string array with more than
// one entry
Method(Hashtable table)
{
//This would throw an exception in the event that just a single string is in the table entry:
//string[] chosenAgenciesIDs = (string[])table[key];

// Need to test to see if i've got just one string or an array of strings
string[] chosenAgenciesIDs;
System.Type entryType = table[key].GetType();
if (entryType.Name == "String")
{
chosenAgenciesIDs = new string[]{table[key].ToString()};
}
else
{
chosenAgenciesIDs = (string[])table[key];
}

foreach(string strAgencyID in chosenAgenciesIDs)
{
int intAgencyID = Convert.ToInt32(strAgencyID);
// do some stuff with the string
}
}

Now, this DID work but its cumbersome and untidy. But then i found a post proclaiming the use of the IEnumberable interface to solve my problem:



// Within this Hashtable, against a given key, i would recieve from the client either a
// single string (note: not a string array with one entry) OR a string array with more than
// one entry
Method(Hashtable table)
{
//This would throw an exception in the event that just a single string is in the table entry:
//string[] chosenAgenciesIDs = (string[])table[key];


IEnumerable agencyList = (IEnumerable)table[key];
foreach(string strAgencyID in agencyList)
{
int intAgencyID = Convert.ToInt32(strAgencyID);
// do some stuff with the string
}
}

However, in the event that just a single string is in the table entry, IEnumberable will then proceed to create an enumeration of chars that make up the string, so the highlighted code will actually throw an exception:

Unable to cast object of type 'System.Char' to type 'System.String'

No comments:

Post a Comment