How to return a list of strings in C#
Solution 1
List<string> or string[] are the best options.
Here is a sample method that returns list of strings :
public static List<string> GetCities()
{
List<string> cities = new List<string>();
cities.Add("Istanbul");
cities.Add("Athens");
cities.Add("Sofia");
return cities;
}
Solution 2
You can store a fixed list of strings as an array:
string[] myStrings = {"Hello", "World"};
Or a dynamic list as a List<string>
:
List<string> myStrings = new List<string>();
myStrings.Add("Hello");
myStrings.Add("World");
Solution 3
In C# you can simply return List<string>
, but you may want to return IEnumerable<string>
instead as it allows for lazy evaluation.
Solution 4
There are many ways to represent a list of strings in .NET, List<string> being the slickest. However, you can't return this to COM because:
COM doesn't understand .NET Generics
FxCop will tell you that it's bad practice to return an internal implementation of something (List) rather than an abstract interface (IList / IEnumerable).
Unless you want to get into really scary Variant SafeArray objects (not recommended), you need to create a 'collection' object so that your COM client can enumerate the strings.
Something like this (not compiled - this is just an example to get you started):
[COMVisible(true)]
public class CollectionOfStrings
{
IEnumerator<string> m_enum;
int m_count;
public CollectionOfStrings(IEnumerable<string> list)
{
m_enum = list.GetEnumerator();
m_count = list.Count;
}
public int HowMany() { return m_count; }
public bool MoveNext() { return m_enum.MoveNext(); }
public string GetCurrent() { return m_enum.Current; }
}
(See http://msdn.microsoft.com/en-us/library/bb352856.aspx for more help)
Solution 5
Yesterday you asked how to do this via COM interop! Why the step backward?
How to return a collection of strings from C# to C++ via COM interop
Cute
Updated on July 09, 2022Comments
-
Cute almost 2 years
Can anybody tell me How to store and return List of Strings.
I am asked this Because i have written a function which returns Collection of strings and I want to prepare a COM for that one and need to consume that COM(to get the returned list ) in VC++ where I can extend some functionality using that list of strings. I hope this would be clear.