StringCollection इंडेक्सर के माध्यम से शून्य-आधारित इंडेक्स द्वारा स्ट्रिंग्स तक पहुंच प्रदान करता है। यह केवल स्ट्रिंग मान स्वीकार करता है, टाइप सुरक्षा प्रदान करता है।
उदाहरण 1: तत्व पढ़ना
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection strCol = new StringCollection();
String[] strArr = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
Console.WriteLine("StringCollection elements...");
foreach (string str in strArr)
{
Console.WriteLine(str);
}
strCol.AddRange(strArr);
Console.WriteLine("Element at 5th index = " + strCol[5]);
}
}
आउटपुट
StringCollection elements... A B C D E F G H Element at 5th index = F
उदाहरण 2: तत्व पढ़ना और अपडेट करना
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection strCol = new StringCollection();
String[] strArr = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
Console.WriteLine("StringCollection elements...");
foreach (string str in strArr)
{
Console.WriteLine(str);
}
strCol.AddRange(strArr);
Console.WriteLine("Element at 5th index = " + strCol[5]);
strCol[5] = "M";
Console.WriteLine("Element at 5th index (updated) = " + strCol[5]);
}
}
आउटपुट
StringCollection elements... A B C D E F G H Element at 5th index = F Element at 5th index (updated) = M
StringCollection आंतरिक रूप से ArrayList का उपयोग करता है। इंडेक्सर O(1) एक्सेस प्रदान करता है। अमान्य इंडेक्स ArgumentOutOfRangeException फेंकता है। null मान अनुमत हैं। आधुनिक कोड में List<string> पसंद किया जाता है।