#region Copyright 2009-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using CSharpTest.Net.Interfaces;
namespace CSharpTest.Net.Collections
{
/// A readonly list of T
public class ReadOnlyList : IReadOnlyCollection, ICloneable>
{
readonly IList _list;
/// Creates a readonly list of T by copying the enumeration into a List<T>
public ReadOnlyList(IEnumerable collection) : this(new List(collection), false) { }
/// Creates a readonly list of T by copying the collection
public ReadOnlyList(IList list) : this(list, true) { }
/// Creates a readonly list of T creating a copy if desired
public ReadOnlyList(IList list, bool clone)
{
if(!clone)
_list = list;
else
{
T[] items = new T[list.Count];
list.CopyTo(items, 0);
_list = items;
}
}
///
/// Returns the element at the given offset
///
public T this[int index]
{
get { return _list[index]; }
}
///
/// Returns the zero-based index of the item or -1 if not found.
///
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
///
/// Returns true if the list contains the specified element.
///
public bool Contains(T item)
{
return _list.Contains(item);
}
///
/// Returns the collection as an array
///
public T[] ToArray()
{
T[] items = new T[_list.Count];
_list.CopyTo(items, 0);
return items;
}
///
/// Returns an enumeration of the elements in the collection
///
public IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_list).GetEnumerator();
}
///
/// Copy the elements in the collection to the specified array
///
public void CopyTo(Array array, int index)
{
if (array is T[])
_list.CopyTo((T[])array, index);
else
foreach (T item in this)
array.SetValue(item, index++);
}
///
/// Returns the count of items contained in the collection
///
public int Count
{
get { return _list.Count; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return this; }
}
#region ICloneable Members
/// Returns a shallow clone of this object
public ReadOnlyList Clone()
{
return new ReadOnlyList(_list, false);
}
object ICloneable.Clone()
{
return this.Clone();
}
#endregion
}
}