0

I am new to C#. This is a Unity project.

I initialize a room object from Room class with property map of type ArrayList like this:

Room room1 = new Room()
{  
  map = new ArrayList {
    new ArrayList(new int[] { 1, 1 } ),
    new ArrayList(new int[] { 1, 1 } ),
    new ArrayList(new int[] { 1, 1 } )
  }
}

Then I override ToString() method of the class Room

public override string ToString()
{
  return "Room ["+map.Count+","+map[0].Count+"]";
}
Debug.Log(room1); 

results in error:

'object' does not contain a definition for 'Count' and no accessible extension method 'Count' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

if I change ToString override as follows:

{
  return "Room ["+map.Count+","+map[0]+"]";
}

then the result of

Debug.Log(room1); 

is "Room [3,System.Collections.ArrayList]"

thus I came to conclusion that I get the error:

System.Collections.ArrayList does not contain a definition for 'Count'

What is going on?

Kai Light
  • 164
  • 2
  • 11
  • 2
    Is there a reason you are using `ArrayList` rather than `List`? – mjwills Jul 30 '19 at 05:45
  • @mjwills ArrayList looks less verbose to me with my javascript/php background – Kai Light Jul 30 '19 at 05:47
  • 3
    Sure, but if you used `List` then you wouldn't have had to ask this question. `ArrayList` is untyped, slower, and requires manual casting. There is virtually no reason to use it in real life code. This issue is occurring 100% because you chose to use `ArrayList`. Using untyped collections makes sense in JS, which is untyped. It makes less sense in a typed language like C#. – mjwills Jul 30 '19 at 05:48
  • @mjwills if `map[0]` is typed as object rather than an `ArrayList`, then why `Debug.Log(room1[0]);` results in `System.Collections.ArrayList`? – Kai Light Jul 30 '19 at 05:49
  • 1
    If you wrote `var bob = map[0];` then the `bob` **variable** would be typed as `object` (you can verify this by hovering over the word `var`) but `bob`'s **current value** would be of type `ArrayList`. The type of the variable is a **compile time** concept. The type of the object is a **run time** concept. The compiler **cannot know** that `map[0]` has a `Count` property. This is pretty standard for typed languages. See also https://blogs.msdn.microsoft.com/alexghi/2009/05/19/compile-time-type-vs-runtime-type-of-a-variable/ . Also read the new duplicates I added. – mjwills Jul 30 '19 at 05:50
  • @mjwills I did what you suggested and switched to List. The code looks way harder to read/understand to me, but it does work. I also somewhat realized the difference of `compile-time` to `run-time` concepts. Thank you. – Kai Light Jul 30 '19 at 06:10

0 Answers0