Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get the number of strings in StringCollection in C#
The StringCollection class in C# provides a specialized collection for storing strings. To get the number of strings in a StringCollection, use the Count property, which returns an integer representing the total number of elements in the collection.
Syntax
Following is the syntax for accessing the Count property −
int count = stringCollection.Count;
Using Count Property with Basic StringCollection
Example
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]);
Console.WriteLine("Count of strings in StringCollection = " + strCol.Count);
}
}
The output of the above code is −
StringCollection elements... A B C D E F G H Element at 5th index = F Count of strings in StringCollection = 8
Using Count Property with Numeric Strings
Example
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection strCol = new StringCollection();
String[] strArr = new String[] { "10", "20", "30", "40", "50" };
Console.WriteLine("StringCollection elements...");
foreach (string str in strArr) {
Console.WriteLine(str);
}
strCol.AddRange(strArr);
Console.WriteLine("Count of strings in StringCollection = " + strCol.Count);
}
}
The output of the above code is −
StringCollection elements... 10 20 30 40 50 Count of strings in StringCollection = 5
Dynamic Count Tracking
Example
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection strCol = new StringCollection();
Console.WriteLine("Initial count: " + strCol.Count);
strCol.Add("First");
Console.WriteLine("After adding 1 element: " + strCol.Count);
strCol.AddRange(new string[] {"Second", "Third", "Fourth"});
Console.WriteLine("After adding 3 more elements: " + strCol.Count);
strCol.Remove("Second");
Console.WriteLine("After removing 1 element: " + strCol.Count);
}
}
The output of the above code is −
Initial count: 0 After adding 1 element: 1 After adding 3 more elements: 4 After removing 1 element: 3
Conclusion
The Count property of StringCollection provides an efficient way to get the number of strings in the collection. It automatically updates as elements are added or removed, making it useful for dynamic collections and validation logic.
Advertisements
