1

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?

2
  • If the underlying object is what you say it is, a simple cast should work MessageBox.Show(((string[])data)[0]); Commented Jul 17, 2014 at 19:10
  • 1
    What is CarregarDadosUsuario actually typed return - that is, what is the method signature? (I would hope it was an Array/IEnumerable/custom of some sort.) If it isn't object, you might be doing this The Hard Way by slopping it into such a variable. If it is unfortunately typed to return an object, what is the type of the actual object that is returned? Commented Jul 17, 2014 at 19:10

2 Answers 2

2

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.

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

4 Comments

I have both strings and integers.
Have updated my answer. You will have to cast the strings and integers in the array accordingly, of course.
And it will crash when indexing. Why not just not leave the result null and check for it? Edit: ToString would be semi-sufficient.
@leppie Could do, I suppose :) Either way he'll have to check for something
1

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]);

Comments

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.