And then I needed an indexer for my type safe collection

Todays task was to export the type safe collection over a web service boundary. This means that the XmlSerializer needs to be able to run on the collection. Initially I got this error message:

    You must implement a default accessor on
    xxxWebService.Service1+ThingieCollection because it inherits from
    ICollection.
    Description: An unhandled exception occurred during the execution of
    the current web request. Please review the stack trace for more
    information about the error and where it originated in the code.
    
    Exception Details: System.InvalidOperationException: You must
    implement a default accessor on
    xxxWebService.Service1+ThingieCollection because it inherits from
    ICollection.
    

The solution was to add an “indexer” to the collection implementation, as so:

public class ThingBase
{
}

public class Thingie : ThingBase
{
	public string m_val;
	public Thingie(string val)
	{
		m_val = val;
	}
}

public class OtherThingie : ThingBase
{
	public int m_val;
	public OtherThingie(int val)
	{
		m_val = val;
	}
}

public class NotAThingie
{
}

public class ThingieCollection : CollectionBase
{
	public void Add(ThingBase a)
	{
		List.Add(a);
	}

	public ThingBase this [int i]
	{
		get
		{
			return (ThingBase) List[i];
		}
		set
		{
			if ( i >= Count )
			{
				Add(value);
			}
			else
			{
				List[i] = value;
			}
		}
	}
}