'Object type is object[], but when using .length it is now apparently an object
This function is supposed to return an object array of object arrays,
public static object[] testmethod()
{
var connection = ConnectDB("notesDB.db");
connection.Open();
var command = connection.CreateCommand();
command.CommandText = @"SELECT noteTitle, noteContents, noteID FROM userNotes WHERE noteUserID = '1'";
var reader = command.ExecuteReader();
List<object> noteDetails = new List<object>();
while (reader.Read())
{
Object[] values = new Object[reader.FieldCount];
reader.GetValues(values);
noteDetails.Add(values);
}
return noteDetails.ToArray();
}
When using
NoteInfoArray = NotesModel.testmethod();
foreach (var item in NoteInfoArray)
{
Trace.WriteLine(item);
}
or
for (int i = 0; i < NoteInfoArray.Length; i++)
{
Trace.WriteLine(NoteInfoArray[i]);
}
over this I get the return
System.Object[]
System.Object[]
System.Object[]
System.Object[]
System.Object[]
But when I try to index these supposed object arrays, I get
CS0021 Cannot apply indexing with [] to an expression of type 'object'
Anyone have any ideas as to how I can fix this?
Solution 1:[1]
NoteInfoArray[] is an array of objects, thus it has a .Length property.
When you use object.ToString() then (unless .ToString() has been overridden) it will return the name of the type.
This is what you are seeing when you call Trace.WriteLine(NoteInfoArray[i]);.
However, the declared type of NoteInfoArray[i] is still object, hence if you try to index it you will get a syntax error.
In order to index it properly, you will have to actually cast it to the underlying type like so:
for (int i = 0; i < NoteInfoArray.Length; i++)
{
Trace.WriteLine(NoteInfoArray[i]);
object[] asArray = (object[])NoteInfoArray[i];
// Now you can index into asArray
}
Solution 2:[2]
To fix it, it is enough to cast the object to an array of objects
for (int i = 0; i < NoteInfoArray.Length; i++)
{
Console.WriteLine(NoteInfoArray[i]);
var elementArray = (object[])NoteInfoArray[i];
for (int j = 0; j < elementArray.Length; j++)
{
Console.WriteLine("\t{0}", elementArray[j]);
}
}
The error fire because object is not iterable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matthew Watson |
| Solution 2 | Pivazi Z. |
