Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

October 2010 - Posts

An example of Arrays,ArrayList,generic collections in an ASP.Net application

In one of my ASP.Net seminars I have been asked to provide a small sample/example on working with a group of custom objects.

I have created a small example/site with ASP.Net & C# and  thought it might be a good idea to share it with you.

More specifically I have been asked to create a small ASP.Net web site where I will demonstrate the use of arrays with objects,ArrayLists with objects and generic collections with objects.

I know some people will find this post's contents pretty basic but for those junior developers out there, I hope it is really helpful.

Let's demonstrate that using our usual methodology, a hands-on step by step example.

We will start with an array of objects first.

1) Launch Visual Studio 2010/2008/2005. Express editions work fine.

2) Create a new empty website and give it an appropriate name.Choose C# as the development language.

3)  Add a new item in your site, a web form item. Leave the default name, so it is called Default.aspx.

4) Add a new item in your site, a class file.Name the class file Person.cs.

5) The whole code for the Person.cs class follows

public class Person
{

    #region  define public properties of my person class

    public string FirstName { getset; }

    public string LastName { getset; }

    public string Email { getset; }

    public decimal Height { getset; }

    public decimal Weight { getset; }


    #endregion

    #region calculatecurrentage

    public int CalculateCurrentAge(DateTime dob)
    {

        int years = DateTime.Now.Year - dob.Year;

        if (DateTime.Now.Month < dob.Month || 
(DateTime.Now.Month == dob.Month && DateTime.Now.Day < dob.Day))
            years--;

        return years;
    }


    #endregion

    public string DisplayFullName()
    {
        string info;
        info = "FullName is: " + FirstName + " " + LastName;
        return info;

    }

}

 

6) So as you see this is a fairly easy class with 5 public properties and 2 public methods. Place the Person.cs in the special folder App_Code.If this special folder is not created, you can create it yourself by right-clicking on your site's name and from the submenu click "Add ASP.Net Folder".

I am not using public fields. I want you to make a note of that. I am using C# 3.0 syntax using Auto-implemented properties. The compiler creates the appropriate private fields. In general it is a good practice to have your fields private and make the properties public. I also have created 2 easy to understand public methods.

7) So now we do have our custom object/type. Let's see how to group these objects in an array of objects. In the default.aspx inside the Page_Load event handling routine type,

        Person[] people = new Person[3];

  Person p1 = new Person();

  p1.FirstName = "Nikos";
        p1.LastName = "Kantzelis";
        p1.Email = "nikolaosk@hotmail.com";
        p1.Height = 1.78m;
        p1.Weight = 88.5m;
   

        Person p2 = new Person();

        p2.FirstName = "James";
        p2.LastName = "Rowling";
        p2.Email = "jamesr@hotmail.com";
        p2.Height = 1.98m;
        p2.Weight = 98.25m;

        Person p3 = new Person();

        p3.FirstName = "George";
        p3.LastName = "Graham";
        p3.Email = "graham@yahoo.co.uk";
        p3.Height = 1.88m;
        p3.Weight = 81.5m;

        people[0] = p1;
        people[1] = p2;
        people[2] = p3;

        for (int i = 0; i < 3; i++)
        {
            string peopleinfo;
            peopleinfo = people[i].DisplayFullName();
            Response.Write(peopleinfo);
            Response.Write("<br/>");
        }

8) Run your application and see the fullname of our Person object printed in the screen. The code I have written in the Page_Load routine is not difficult to follow.

First I create a new array of Person objects and set the size to 3 elements.Then I create 3 instances of the Person class and fill in the public properties with random values.

Then I place those reference variables (p1-p3) inside our array (people).

Finally I loop inside the array and print the fullname of each object by calling the DisplayFullName() method of the Person class.

This works fine but there are some limitations. One of them is that you have to know beforehand how many items we must place in the array.

An alternative way is to use  ArrayLists.

So let's move on to our more efficient way of storing group of custom objects. In this example we will use an ArrayList object.

9) Drag and drop a button in the default.aspx page. Leave the default name. Double click on the button to create the Button1_Click event handling routine.Comment out all of your code in the Page_Load event handling routine.

10)  We will use of course the Person class. Inside the Button1_Click event handling routine type,

        ArrayList people = new  ArrayList();

        Person p1 = new Person();

        p1.FirstName = "Nikos";
        p1.LastName = "Kantzelis";
        p1.Email = "nikolaosk@hotmail.com";
        p1.Height = 1.78m;
        p1.Weight = 88.5m;


        Person p2 = new Person();

        p2.FirstName = "James";
        p2.LastName = "Rowling";
        p2.Email = "jamesr@hotmail.com";
        p2.Height = 1.98m;
        p2.Weight = 98.25m;

        Person p3 = new Person();

        p3.FirstName = "George";
        p3.LastName = "Graham";
        p3.Email = "graham@yahoo.co.uk";
        p3.Height = 1.88m;
        p3.Weight = 81.5m;

        people.Add(p1);
        people.Add(p2);
        people.Add(p3);

        foreach (object item in people)
        {
            Person myperson = (Person)item;
       
            Response.Write(myperson.DisplayFullName());
            Response.Write("<br/>");

        }

11) Run your application and see the results exactly as before when we used a simple Array object.

Make sure you have added the using System.Collections; in the top of your file.

I am just creating a new instance of the ArrayList object

ArrayList people = new  ArrayList();

Then I create 3 intances of the Person custom object and fill in the values as previously.Then I use the Add method to add those objects in my ArrayList object.

The Add method of the Arraylist class accepts a parameter of type Object.So when we add a Person object as we do in our example that object has to be casted to an instance of type Object.

This process is also known as boxing. The reverse process is known as unboxing. This pair of processes has impact on application’s performance.

Then I just loop through the items and print the relevant information.

Now add another object in the ArrayList. We can do that with ArrayLists but not with simple Arrays of objects.You type the following code just after the foreach block of code,

        Person p4 = new Person();
        p4.FirstName = "Mary";
        p4.LastName = "Stewart";
        p4.Email = "marystewart@yahoo.co.uk";
        p4.Height = 1.71m;
        p4.Weight = 61.5m;
        people.Insert(2, p4);

 12) Now add this code again after you have inserted a 4th object in the array list.

 foreach (object item in people)
        {
            Person myperson = (Person)item;
       
            Response.Write(myperson.DisplayFullName());
            Response.Write("<br/>");

        }

 13) Run your application, click on the button, and see the new object added in the ArrayList in the correct position.So with ArrayLists we do have more power as developers when it comes to grouping objects in arrays.

 Now let's see a limitation of ArrayLists. Add another class file to your site and name is Animal.cs. The code inside the .cs file should be something like this

public class Animal
{

    public bool isMammal { getset; }

    public string Species { getset; }

    public double Speed { getset; }

    public decimal Height { getset; }

    public decimal Weight { getset; }

}

I am not bothered at this time to add any public methods. Switch back to your default.aspx.cs file and in the end of the Button1_Click event handling routine type something like this

          Animal myanimal = new Animal();
          myanimal.isMammal = true;
          myanimal.Species = "Panthera";
          myanimal.Speed = 56.8;
          myanimal.Height = 0.78m;
          myanimal.Weight = 163;

Now add this line of code just below the instantiation of your animal object.

people.Add(myanimal);

 Compile your application and see tha it compiles just fine.Now if you add this code just after the previous line

 

   foreach (object item in people)
          {
              Person myperson = (Person)item;

              Response.Write(myperson.DisplayFullName());
              Response.Write("<br/>");

          }

and build your application, your application will build just fine. Now run your application and you will get an exception (InvalidCastException).It cannot cast something of type Animal to Person.

 

14) Now let's improve our code with the use of generic collections. With .Net Framework 2.0 generic collections were introduced. A generic collection is basically a container that can be used to store objects of any class. What we do is we simply define a generic version of ArrayList by using the syntax of List<T>. T stands for type parameter, indicating that the type of the member objects in the list has not yet specified. We can replace T with any class or object. T gets replaced by the data type at compile time.

First add another button in the default.aspx page. Leave the default name.Double click on the button to create the Button2_Click event handling routine and type inside it

 List<Person> people = new List<Person>();

        Person p1 = new Person();

        p1.FirstName = "Nikos";
        p1.LastName = "Kantzelis";
        p1.Email = "nikolaosk@hotmail.com";
        p1.Height = 1.78m;
        p1.Weight = 88.5m;


        Person p2 = new Person();

        p2.FirstName = "James";
        p2.LastName = "Rowling";
        p2.Email = "jamesr@hotmail.com";
        p2.Height = 1.98m;
        p2.Weight = 98.25m;

        Person p3 = new Person();

        p3.FirstName = "George";
        p3.LastName = "Graham";
        p3.Email = "graham@yahoo.co.uk";
        p3.Height = 1.88m;
        p3.Weight = 81.5m;

        people.Add(p1);
        people.Add(p2);
        people.Add(p3);

        foreach (Person item in people)
        {
           
            Response.Write(item.DisplayFullName());
            Response.Write("<br/>");

        }

 

Run your code and it will work just fine. The only thing we have changed so far is this line of code

ArrayList people = new  ArrayList();

with this line of code

List<Person> people = new List<Person>();

 and this foreach statement

 foreach (object item in people)
          {
              Person myperson = (Person)item;

              Response.Write(myperson.DisplayFullName());
              Response.Write("<br/>");

          }
 

with this one

   foreach (Person item in people)
        {
           
            Response.Write(item.DisplayFullName());
            Response.Write("<br/>");

        }

We do not need casting anymore. Well that is awesome.

Now let's add an animal object.So just below the code we just typed add,

 Animal myanimal = new Animal();
        myanimal.isMammal = true;
        myanimal.Species = "Panthera";
        myanimal.Speed = 56.8;
        myanimal.Height = 0.78m;
        myanimal.Weight = 163;

        people.Add(myanimal);

 

Try to build this application to see if it compiles. It will fail.It won't compile.Well this is a good thing since now we know (type safety) at compile time that we cannot add our animal object in the people collection.

There are ways to solve this problem but not with generic lists. The point I am trying to make in this post is a simple comparison ways that we group objects, hence a comparison of arrays,ArrayLists and Generic Collections. 

I know these things are pretty basic. So experienced developers please read some of my other posts if you want.For everyone though who wants to build any kind of application (WPF,Silverlight,Console,Window Forms,ASP.Net) must know these things.

Leave a comment ( or email me ) if you need the source code.

Hope it helps!!!

 

More Posts