Tuesday, April 26, 2011

StringCollections in .NET

After some tiresome work, i decided to visit MSDN. Along the way,i manage to take a grip from System.Collections.Specialized StringCollection class.
I was used to List, ArrayList, and etc. After reading MSDN's documentation,I managed to create a simple example.
Code:
  class Program  
    {  
      static void Main(string[] args)  
      {  
        //defined class  
        StringCollections collections = new StringCollections();  
        //.NET collection class  
        StringCollection netcollection = new StringCollection();  
        string[] names = new string[5];  
        //insert five elements  
        for(int i = 0; i <5; i++)  
        {  
          names[i] = "nelson" + (i+1);  
        }  
        //store to stringcollection object  
        netcollection = collections.Employees(names);  
        //navigate collection class  
        StringEnumerator enumerator = netcollection.GetEnumerator();  
        while (enumerator.MoveNext())  
        {  
          Console.WriteLine(enumerator.Current);  
        }  
        Console.ReadLine();  
      }  
    }  
    internal sealed class StringCollections  
    {  
      public StringCollection Employees(string[] names)  
      {  
        StringCollection collections = new StringCollection();  
        try  
        {  
          collections.AddRange(names);  
        }  
        catch (Exception ex)  
        {          
          throw new Exception(ex.InnerException.Message);  
        }  
        return collections;  
      }  
    }  
The code above,will display the list using Enumerator. You could use foreach or other methods. But I decided the Enumerator object..
Cheers!!!

0 comments:

Post a Comment