-3

I have a class that contains properties into a "List" though I want to use an array or ArrayList. I am sure their are some restrictions on using either. I provided an example of both approaches below; which would be a better approach? Which approach is faster in terms of memory usage?

public class Cat
{
    public int CatId { get; set; }
    public string CatName { get; set; }

public static void ListCats()
{
    ArrayList cats = new ArrayList();

    Cat cat = new Cat();

    cat.CatId = 1;
    cat.CatName = "Jim";
    cats.Add(cat);

    cat.CatId = 2;
    cat.CatName = "Sally";
    cats.Add(cat);
}
}

I understand ArrayList comes with methods that make it easier for doing different things with a list. Also, ArrayList is not a strongly typed collection. However, would it make more sense to be explicit with a list if the values in the list need to be pulled regularly from the user? What are some cases when array should be used instead?

public class Cats
    {
      public string CatName { get; set; }
      public int CatId { get; set; }

    }

public static void ListCats()
    {
      Cats[] cats = new Cats[];

      Cats[] = { 

                 CatName = "Charlie", CatId = 1;
                 CatName = "Missy", CatId = 2;

               }
    }
Juan Davila
  • 61
  • 1
  • 11
  • It is unclear what you are asking. Arrays and Lists can be used "quite similiar", so there is (from a usage point of view) just a very small difference, as these collections can be converted into each other at any time. – dognose Dec 08 '18 at 21:33
  • In the first snippet, change the `ListCats()`: `List cats = new List() { new Cats() { CatName = "Charlie", CatId = 1 }, new Cats() { CatName = "Missy", CatId = 2 } };` Your `Cats` class should be `Cat`, so your list would be a `List` to which you `.Add()` a `new Cat()` or `AddRange(Enumerable)`. Your `ListCats()` could return a `List` instead of `void`. – Jimi Dec 08 '18 at 21:33
  • The code you posted isn't correct. – Tobias Tengler Dec 08 '18 at 21:34
  • [`Which approach is faster?`](https://ericlippert.com/2012/12/17/performance-rant/) – L.B Dec 08 '18 at 21:40

1 Answers1

0

Iterating through arrays is always faster, however Lists are way more flexible and more useful in day to day uses. Use arrays when u really need that extra tiny bit of optimization (e.g. game development), otherwise i would always go with the Lists.

If you need more information please refer to the link below:

When should I use a List vs a LinkedList

Also if u want to initialize collection of objects use the following syntax

List<Cats> cats = new List<Cats>
{
    new Cats { CatName = "Charlie", CatId = 1 },
    new Cats { CatName = "Missy", CatId = 2 },
};
Kacper S.
  • 51
  • 1
  • 6