Share via


How to cast object[] to string []

Question

Wednesday, May 25, 2011 9:05 AM

Hello

             How to cast object[] to string [] 

 

Regards

It's Me

All replies (9)

Wednesday, May 25, 2011 12:32 PM ✅Answered | 2 votes

To cast object O to type T, you use the syntax: (T)O

object[] objectArray = new[] { "first", "second", "third", "42" };
string[] stringArray = (string[])objectArray;

Wednesday, May 25, 2011 12:56 PM ✅Answered | 2 votes

To cast O to type T, you can always use the cast operator (T)O. I didn't say casting couldn't fail.

If the question had been "how do I divide an integer by another", I would have said to use the syntax A/B. Even though 1/0 raises an exception.

The Cast<T> method doesn't cast an array object to the type T[]. It casts each item of the source array to type T.

Even this is not right. In purely C# vocabulary, it doesn't cast them. It unboxes values or does a reference conversion. C# casting is more polyvalent: it can do numeric conversion or call user-defined conversions.


Wednesday, May 25, 2011 9:18 AM | 3 votes

      object[] o = new object[] {"A","B","C" };
      string[] s = o.Cast<string>().ToArray();

 

But here, you cast each element by using the System.Linq.Cast-Method... That means: you do not "cast", you create a new array with string-elements.


Wednesday, May 25, 2011 9:43 AM | 1 vote

To add to GreatVolk` post:

      //1.
      object[] objArray = { "A", "B", "C" };
      string[] strArray = objArray.Cast<string>().ToArray();

      //2.
      object[] objArray2 = { "A", null, 1, false };
      foreach (object obj in objArray2)
      {
        if (obj != null)
        {
          if (obj.GetType() == typeof(string))
          {
            //strings values in here
          }
        }
      }

 

2nd example shows that every object cannot be a string. So here is the code , which checks which value from an array is string.

Mitja


Wednesday, May 25, 2011 12:38 PM | 2 votes

..... No, only sometimes!

      object[] o1 = new string[] { "A", "B", "C" };
      object[] o2 = new object[] { "A", "B", "C" };
      string[] s1 = (string[])o1; //Good
      string[] s2 = (string[])o2; //Invalid Cast Exception

Wednesday, May 25, 2011 1:23 PM

:D

That's right, you always can cast everything to everything else, if it may be technially possible.

I hope It_s Meee will not get confused by proposal, just because I assumed, that he'd like to cast without exception...  :)


Thursday, May 26, 2011 12:41 PM | 1 vote

It's difficult to know exactly what is needed with such a short question.

Here is a possible answer which shouldn't fail:

string[] stringArray = objectArray.Select(o => o.ToString()).ToArray();

Thursday, May 26, 2011 2:18 PM

What in case if the object is not type of string? Lets say its type of bool?Mitja


Thursday, May 26, 2011 4:10 PM

My last reply should not fail for most object types.