Marcelo Camargo
Marcelo Camargo

Reputation: 2298

C# - Convert Object to Array to get Data by Index

I have a webservice that returns me an object with data

 object data = _wsUsuario.CarregarDadosUsuario(_view.Usuario);

This object, called data, returns me the following:
[0] 84
[1] Marcelo Camargo
[2] [email protected]
[3] 2

If I try to do

MessageBox.Show(data[0]);

Then the compiler says me:

Cannot apply indexing to an expression of type 'object'. I searched and wonder if there is a way to convert this object of strings and integers to an array. Can you give me a hand?

Upvotes: 1

Views: 466

Answers (2)

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

Assuming the data is an array of strings, then you would need to cast it accordingly:

object[] oData = (data as object[]) ?? new object[0];

This will TRY to cast to object[] but if it isn't castable, it will return null and the null coalescing operator ?? will return an empty object array instead.

Upvotes: 2

Amir Popovich
Amir Popovich

Reputation: 29836

An object doesn't have an indexer. An array does.

I think you downcasted the functions return type from a specific strong type object(some kind of array) into a basic 'object'.

What should happen:

// res should be an array
CarregarDadosUsuarioReturnType res = _wsUsuario.CarregarDadosUsuario(_view.Usuario);
MessageBox.Show(res[0]);

If, for any reason this service implicitly recieves an object simply cast this into:

object data = _wsUsuario.CarregarDadosUsuario(_view.Usuario);
var arr = data as ArrType[]; // where ArrType = the array type.
MessageBox.Show(arr[0]);

Upvotes: 1

Related Questions