jump to navigation

.NET 2.0 Generics, … i am in love with it…. August 24, 2007

Posted by addisu in Software - .NET 2.0, Software - .NET General, Software - C#.
trackback

I had a number of collection classes with similar functionalities like this…

public class PermissionCollectionEntity : IEntity
{
List<PermissionEntity> list;

public PermissionCollectionEntity()
{
this.list = new List<PermissionEntity>();
}

public List<PermissionEntity> Items
{
get
{
return this.list;
}
}

public void Add(PermissionEntity entity)
{
if (entity != null)
{
this.list.Add(entity);
}
}

public Boolean Remove(PermissionEntity entity)
{
if (entity != null && this.list.Contains(entity))
{
return this.list.Remove(entity);
}
else
{
return false;
}
}

public void RemoveAt(int index)
{
if (this.list.Count > index && index >= 0)
{
this.list.RemoveAt(index);
}
}

public void Clear()
{
if (this.list.Count > 0)
{
this.list.Clear();
}
}

public int Count
{
get
{
return this.list.Count;
}
}
}

Now i am replacing those Collection classes with one Generics class like this…

public class TCollectionEntity<T> : IEntity
where T : IEntity
{
List<T> list;

public TCollectionEntity()
{
this.list = new List<T>();
}

public List<T> Items
{
get
{
return this.list;
}
}

public void Add(T entity)
{
if (entity != null)
{
this.list.Add(entity);
}
}

public Boolean Remove(T entity)
{
if (entity != null && this.list.Contains(entity))
{
return this.list.Remove(entity);
}
else
{
return false;
}
}

public void RemoveAt(int index)
{
if (this.list.Count > index && index >= 0)
{
this.list.RemoveAt(index);
}
}

public void Clear()
{
if (this.list.Count > 0)
{
this.list.Clear();
}
}

public int Count
{
get
{
return this.list.Count;
}
}
}

I can re-use this collection for all my Entity classes…I can also enforce the Entity Classes shouldimpliment certain Interfaces…

Cool stuff…

Comments»

No comments yet — be the first.