0

What is the difference between a Specialized String Collection and a Generic String List in C#?

And how to convert a Specialized one into a Generic one?

System.Collections.Specialized.StringCollection specialized = new System.Collections.Specialized.StringCollection() { "s123", "s321" };

System.Collections.Generic.List<string> generic = new System.Collections.Generic.List<string>() { "g123", "g321" };
Anas Alweish
  • 2,818
  • 4
  • 30
  • 44
Dave
  • 1,912
  • 4
  • 16
  • 34
  • 12
    StringCollection was added before generics were introduced. Use `List`. – Lasse V. Karlsen May 22 '19 at 13:11
  • @AnasAlweish my question also ask what is the difference between the two. – Dave May 22 '19 at 13:15
  • 1
    There are many, does it matter? You should be using `List`, does it matter what StringCollection would do or how it does it? For one difference, `List` implements `IEnumerable`, whereas `StringCollection` only implements `IEnumerable` (the non-generic one). – Lasse V. Karlsen May 22 '19 at 13:17
  • The core point of the two aren't different though. Both implement a dynamic list of strings you can add strings to. – Lasse V. Karlsen May 22 '19 at 13:17
  • 1
    As to your second question, `specialized.Cast().ToList()` will do. There is no real use case for `StringCollection` in new code; don't use it unless you have to interoperate with older code. – Jeroen Mostert May 22 '19 at 13:22
  • @JeroenMostert this is why I asked, because I working on some old code where methods uses `StringCollection` instead of `List`. So I was wondering why they use `StringCollection` – Dave May 22 '19 at 13:25
  • 1
    Note that if you *are* interoperating with older code, using `StringCollection` where asked for is still a better idea than continuously converting back and forth between `StringCollection` and `List` -- that just eats memory and cycles. You can use `.Cast()` if you need type-safe enumeration on an incidental basis. – Jeroen Mostert May 22 '19 at 13:28
  • 1
    If you want to see the exact differences, take a look at the reference source for [List](https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs) (btw. it is somewhat telling that this doesn't even list the `System.Collections.Specialized` namespace) and [StringCollection](https://github.com/microsoft/referencesource/blob/master/System/compmod/system/collections/specialized/stringcollection.cs). – Corak May 22 '19 at 13:30
  • 1
    take a look at this [to know diff](http://www.vbforums.com/showthread.php?640282-System-Collections-Specialized-StringCollection-vs-System-Collections-Generic-List(Of) – Gowtham Alan May 22 '19 at 13:36

0 Answers0