Accessing object[x] index in C# gives cast object to object[] error
I have a simple piece of code:
object[] result = this.getData("baseLogin", args);
if (result.Count() > 0)
return result[0];
Method getData
returns object[] ofcourse.
result[0]
gives following error:
Cannot implicitly convert开发者_开发技巧 type 'object' to 'object[]'.
An explicit conversion exists (are you missing a cast?)
Why does it treat object[] as object and wants to convert it to object[]?
I assume that the return type of your method is object[]
and not object
:
object[] DoSomething()
{
object[] result = this.getData("baseLogin", args);
if (result.Count() > 0)
return result[0]; // <- This line returns an object. But the return type
// of the method is object[]
}
It depends on what you really need.
If you really only want to return the first object, change your methods return type to object
. If - for some reason - you need to return an object[]
with only the first element in it, change the return statement to this: return new object[] { result[0] };
.
If by any chance getData
is returning array of arrays, meaning each item in the result array is array by itself, the compiler can't know that... you have to convert it explicitly like this:
if (result.Count() > 0)
return (object[])result[0];
This will give run time error in case the item is something else.
精彩评论