Hello,
I have started to play with Generics in C# 2.0. I know what they are about but still a little unsure on how to use Generics appropriatly. Below is my first attempt at using Generics. If I were to use code as show below, am I realizing the benefits of Generics (i.e. type-safety, performance improvement, no need to (un)box, etc)?
Thanks
public class EmployeeCollection : IEnumerable<Employee>
{
List<Employee> m_empCollection = new List<Employee>();
public EmployeeCollection()
{}
public void Add(Employee newItem)
{
m_empCollection.Add(newItem);
}
public void Remove(Employee oldItem)
{
m_empCollection.Remove(oldItem);
}
public Employee this[int index]
{
get { return m_empCollection[index]; }
}
public int Count
{
get { return m_empCollection.Count; }
}
#region IEnumerable<Employee> Members
public IEnumerator<Employee> GetEnumerator()
{
return m_empCollection.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return m_empCollection.GetEnumerator();
}
#endregion
}
Type-safety - yes. Using List<Employee> instead of ArrayList ensures type safety.
Performance improvement - minimal. Code working with List<Employee> doesn't need to make runtime casting (like ArrayList requires), this gives some performance improvement.
Unboxing - doesn't apply here, because Employee is reference type.
Assuming that Employee is structure (value type):
Type-safety - yes.
Performance improvement - significant. Code working with List<Employee> doesn't need to make runtime casting (like ArrayList requires) and doesn't need to make boxing. ArrayList requires boxing for value type, because it works with Objects.
Unboxing - using List<Employee> prevents unboxing.
Performance improvement and no unboxing - this also applies for primitive value types, like int, double etc.
Notice that List<Employee> class itself implements IEnumerable<Employee>, it can do all that your EmployeeCollection class does.