Provides a simple extension to System.Collections.Specialized.StringCollection allowing the caller to call the ToArray() method to get a string[] which is commonly used with other parts of the framework. For example if the code is using the string.Split functions and wanted to call the SplitQuotedString function in it place the SplitQuotedString function returns a more specialised StringCollection however this method allows the caller to ToArray() to expose the same construct as the existing String.Split method allowing for a straight replace with the string.Split function

Namespace:  CA.Common.Text
Assembly:  CA.Common (in CA.Common.dll) Version: 1.0.0.0 (1.0.0.0)

Remarks

source code for method provided below

CopyFull Source Code for the ToArray method in the StringCollection class
public string[] ToArray()
{
    string[] result = new string[Count];
    CopyTo(result, 0);
    return result;
}

Examples

Unit Test to test the code above:

CopyUnit Test to CheckStringCollectionToArray
[Test]
public void CheckStringCollectionToArray()
{
    StringCollection sc = new StringCollection();
    sc.Add("Item1");
    sc.Add("Item2");
    sc.Add("Item3");
    // create a string array from the collection
    string[] AsArray = sc.ToArray();
    // test to see if the counts are the same
    Assert.AreEqual(sc.Count, AsArray.Length);
    for (int i =0;i< sc.Count; i++)
    {
        // check to see if every element is the same. 
        Assert.AreEqual(sc[i], AsArray[i]);
    }
}

[Test]
public void StringCollectionToAndFromArray()
{

    // Dim up a new test array of countries
    String[] countryTestArr = new [] { "New Zealand", "Australia", "United States", "England", "India" };

    StringCollection countryTestCol = new StringCollection();

    // This is the inverse of the ToArray function ie putting a string array into the StringCollection.
    countryTestCol.AddRange(countryTestArr);

    // Now Assert that the array has copied correctly testing each value and it order
    for (int i = 0; i < countryTestCol.Count; i++)
    {
        // check to see if every element is the same. 
        Assert.AreEqual(countryTestCol[i], countryTestArr[i]);
    }

    // Copy the data out of the array
    String[] countryTestArr2 = countryTestCol.ToArray();

    // assert that the new array is the same as the orginal array in values. 
    for (int i = 0; i < countryTestArr2.Length; i++)
    {
        // check to see if every element is the same. 
        Assert.AreEqual(countryTestArr2[i], countryTestArr[i]);
    }
}

See Also