- C# Lists Introduction
- C# Lists String Repository
- C# Lists Book Repository
- C# Lists of Class Objects
- C# Lists of Class Objects 2
First we can create a list of strings in another class, instead of putting the list right in the Main program. Also we don’t have a class of our own types, like Books or People. Here we are just using strings. We have a class called StringRepository. We have a method called GetStrings(). In that method we return a list of strings. We use object initialization syntax to populate the list with some sample strings.
We have a method called GetStrings() in our class StringRepository. It returns a new list of strings.
Class StringRepository
using System.Collections.Generic; namespace ListOfStringsRepository { class StringRepository { public List<string> GetStrings() { return new List<string>() { "hey", "hi", "dude" }; } } }
Looking at our Main program in C#, we can use the foreach to go through. We need to instantiate our StringRepository class. Next we need to create a variable that will store our list of strings and call it strlst.
using System; namespace ListOfStringsRepository { class Program { static void Main(string[] args) { StringRepository myStrings = new StringRepository(); // instantiate List<string> strlst = myStrings.GetStrings(); foreach (string s in strlst) { Console.WriteLine(s); } } } }
Refactoring
We can shorted our code a bit and get the exact same result.
using System; namespace ListOfStringsRepository { class Program { static void Main(string[] args) { //StringRepository myStrings = new StringRepository(); // instantiate //List<string> strlst = myStrings.GetStrings(); // // we can shorten our code and refactor it to use the line below // instead of the two lines above. var st = new StringRepository().GetStrings(); foreach (string s in st) { Console.WriteLine(s); } } } }