Home > OS >  Object type is object[], but when using .length it is now apparently an object
Object type is object[], but when using .length it is now apparently an object

Time:03-13

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?

CodePudding user response:

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
}

CodePudding user response:

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.

  • Related