Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object to array type [duplicate]

Tags:

c#

I am passing an array as an object in a web method.How can I convert object to an array in web method

public static string sample(object arr)
{
    string[] res= (string[])arr; //convertion object to string array
    return "";
}

I getting error like this

An exception of type 'System.InvalidCastException' occurred in Flair.dll but was not handled in user code

like image 322
Safeena Avatar asked Mar 05 '15 09:03

Safeena


People also ask

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() . Note that the Object.keys() method has been available since ECMAScript 2015 or ES6, and the Object.values() and Object.entries() have been available since ECMAScript 2017.

How do you convert an object to an array in Python?

Using numpy.asarray() , and true (by default) in the case of np. array() . This means that np. array() will make a copy of the object (by default) and convert that to an array, while np.

How do you change an object to an array in react?

data convert to array by using useState([]) as initial value and convert to object by using useState({}) .

How do you turn an object into a String?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.


2 Answers

Simplest method:

public static string[] Convert(object input)
{
  return input as string[];
}

But You have to validate input if you can cast that way, or cast to array of objects and call ToString() on each element

like image 136
Sławomir Pawluk Avatar answered Sep 23 '22 20:09

Sławomir Pawluk


When you downcast you need to check :

public static string sample(object arr)
{
    string[] res=   arr as string[];  
   if (res!=null)
       {
            //ok to continue
       }
   else
      {
         //arr is not string[]
      }
    return "";
}

Try to avoid (string[])arr unless you're 100% sure that arr is string[]

like image 38
Royi Namir Avatar answered Sep 26 '22 20:09

Royi Namir