Yesterday, I’ve wrote in C#. I taken the code from the book.
List.cs

using System;
public class List
{
	const int defaultCapacity = 4;

	T[] items;
	int count;

	public List(int capacity = defaultCapacity)
	{
		items = new T[capacity];
	}

	public int Count
	{
		get{return count;}
	}

	public int Capacity
	{
		get{return items.Length;}
		set
		{
			if(value < count) value = count;
			if(value != items.Length)
			{
				T[] newItems = new T[value];
				Array.Copy(items, 0, newItems, 0, count);
				items = newItems;
			}
		}
	}

	public T this[int index]
	{
		get
		{
			return items[index];
		}
		set
		{
			items[index] = value;
			OnChanged();
		}
	}

	public void Add(T item)
	{
		if(count == Capacity) Capacity = count * 2;
		items[count] = item;
		count++;
		OnChanged();
	}

	protected virtual void OnChanged()
	{
		if(Changed != null) Changed(this, EventArgs.Empty);
	}

	public override int GetHashCode()
	{
		return this.GetHashCode();
	}

	public override bool Equals(object other)
	{
		return Equals(this, other as List);
	}

	static bool Equals(List a, List b)
	{
		for(int i = 0; i a, List b)
	{
		return Equals(a, b);
	}

	public static bool operator !=(List a, List b)
	{
		return !Equals(a, b);
	}
}

And here is the main entry code to test the code above.
Tests.cs

using System;

class Test
{
	static void Main()
	{
		List list1 = new List(5);
		List list2 = new List(10);

		Console.WriteLine(list1 == list2);
	}
}

In this code, I found two bugs that leads the program to run-time error or result error. Can you find it? :D

2 comments… read them below or add one

Neki Arismi January 13, 2012 at 11:40 am

OHHHH Noessss !!! My Eyes! *blasss ga ngerti*

indam January 30, 2012 at 06:06 am

Sebenarnya aku sering mampir kesini, hanya saja. Ngga ada postingan yang bisa aku komentarin.

Postingan inipun ngga connect di otaku, ya mungkin karena aku ngga pernah pelajarin kali yah? Dan sy yakin bro Ganda pasti bilang, itu simple(sejenisnya) ^^

Leave a Comment