Click here to Skip to main content
15,905,612 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,
I have written the following code:
using System;
using System.Collections;

namespace ArrayList1
{
    class Program
    {
        ArrayList a1 = new ArrayList();

        static void Main(string[] args)
        {
            Program objProg = new Program();
            objProg.a1.Add(10);
            objProg.a1.Add(5.67);
            objProg.a1.Add("abcde");
            objProg.a1.Add('c');
            foreach(int i in objProg.a1)
            Console.WriteLine("i");
        }
    }
}

I am getting run-time exception. Some body please guide me.

Zulfi.

What I have tried:

I did web search but still code not working.
Posted
Updated 27-Mar-20 7:35am

Try:
C#
class Program
{
   static ArrayList a1 = new ArrayList();

   static void Main(string[] args)
   {
      a1.Add(10);
      a1.Add(5.67);
      a1.Add("abcde");
      a1.Add('c');
      foreach (object i in a1)
      {
         Console.WriteLine(i);
      }
   }
}

Key points:
- Creating a new instance of the program class in the Main method to be able to access a class member is not a good practice.
- a1 class variable has to be static to be accessed from a static method.
- In the foreach loop, you cannot declare i as an int since your arraylist does not hold only integer values. The common type which can match an integer, a double, a string and a character is an object.
- Console.WriteLine("i"); will print the letter i instead of the value of the variable i.
 
Share this answer
 
The ArrayList is an old feature, and is deprecated [^] now because it is a very expensive (memory, time to access) way to create a collection of objects of mixed Types, and using it, errors will not occur at compile-time.

Its use is also ... in almost all cases ... a violation of good OOP/SOLID principles: in good practice all these bits of data you are putting into the ArrayList mean something. Use a Class (or Struct) to store your data:
C#
public class Data
{
   public int Number10 { set; get; }

   // ...
}
Or, if you must have a structure where you can add multiple Types at run-time, later versions of C# provide the 'ExpandoObject [^] in the System.Dynamic NameSpace (and, the more complex 'DynamicObject):
C#
dynamic person = new ExpandoObject();
person.Name = "John";
person.Surname = "Doe";
person.Age = 42;

// access by Key
int age = person.Age;

foreach (var kvp in person)
{
    Console.WriteLine($"{kvp.ToString()}");
}

// output in Console Window:
[Name, John]
[Surname, Doe]
[Age, 42]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900