Sep 26 2006

Collections part 2 - incapsulation

Posted by admin under .NET

This is part 2 of this article serie on collections in C# - please start by reading Part 1  

Now what's so good with it? Well for starters we can easily incapsulate some functionality regarding Links:

Say we want to offer a "find" funtion - the GUI code might look like this:



Link oLinkFound = oColl.Find("ASPCode");
if ( oLinkFound != null )
	Console.WriteLine( oLinkFound.Url  );

So, we want to search for the link with name "ASPCode". If found we print out the links url.

Lets look at the implementation:



	public class LinkColl : CollectionBase	
	{
		public Link Find(string sName)
		{
			foreach(Link oLink in this )
				if ( oLink.Name == sName )
					return oLink;
			return null;
		}
...
...
...


While pretty basic, this is a perfect example of incapsulation. Now consider we want to change the match mechanism to NOT be case sensitive. I.e now we get no match for  "aspcode" but rahther the perfect spelling "ASPCode".

We now just need to make the change in ONE single location (also pretent that our collection class is being used from multiple other classes and GUI:s/aspx pages)



		public Link Find(string sName)
		{
			foreach(Link oLink in this )
				if ( oLink.Name.ToLower() == sName.ToLower() )
					return oLink;
			return null;
		}



Download is available in part 4