Using Generics and Inheritance to Simplify Development
page 6 of 9
by Brian Mains
Feedback
Average Rating: 
Views (Total / Last 10 Days): 37978/ 109

Example: Custom String Collection

The built-in StringCollection, defined in the .NET Framework's System.Collections.Specialized namespace, is easy to work with strings, but I wanted the ability to convert a list to/from a string.  Take for instance a comma-separated value string.  I wanted the list to have the ability to convert the comma-separated list to/from a string.  I also wanted to work with other separators as well, such as the vertical bar/pipe (|) or tab (\t), which you normally see data separated by.  Below, an inherited structure adds these features.

Listing 3

namespace Nucleo.Collections
{
  public class StringCollection: StringCollection
  {
    public void FromCommaSeparatedList(string text)
    {
      this.FromSeparatedList(text, ",");
    }
 
    public void FromSeparatedList(string text, string separator)
    {
      string[]items = text.Split(separator.ToCharArray());
      foreach (string item in items)
      {
        if (!string.IsNullOrEmpty(item))
          this.Add(item);
      }
    }
 
    public string ToCommaSeparatedList()
    {
      return ToSeparatedList(",");
    }
 
    public string ToSeparatedList(string separator)
    {
      string list = string.Empty;
 
      for (int i = 0; i < this.Count; i++)
      {
        if (i != 0)
          list += separator;
        list += this[i];
      }
 
      return list;
    }
 
    public static StringCollection FromList(string text, string separator)
    {
      StringCollection collection = new StringCollection();
      collection.FromSeparatedList(text, separator);
      return collection;
    }
  }
}

Note that the class also uses a static method to create a collection from a list string, using a separator defined by the user.  This class now has the ability to convert a string from/to CSV or other formatted data.


View Entire Article

User Comments

Title: Using Generics and Inheritance to Simplify Development   
Name: Meena
Date: 2007-10-26 6:32:53 PM
Comment:
This article help me a lot to learn generics.

Thanks
Title: Great Article!   
Name: Mohammad Azam
Date: 2007-09-28 3:18:52 PM
Comment:
Hi Brain,

Great article as always! Keep up the good work.
Title: Using Generics and Inheritance to Simplify Development   
Name: Brain
Date: 2007-05-12 1:40:08 PM
Comment:
Outstanding article. It was very informative. Thanks dude.
- Uday.D






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-12-05 12:51:46 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search