Object Oriented Programming using C#

(backadmin) #1

Object Oriented Programming using C#
Generic Collections and how to Serialize them


The code below shows an example of the creation of a list. In this case a list of names i.e. Strings.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListOfNames
{
class Program
{
// create names which will store a list of names
private static List<String> names;
static void Main(string[] args)
{
names = new List<String>(); // Create empty list
string name;
for (int i = 0; i < 3; i++) //Enter three names
{
name = Console.ReadLine();
names.Add(name); // Add each name onto list
}
foreach (String n in names) // Itterate through list
displaying each element.
{
Console.WriteLine(n);
}
Console.WriteLine(“Please enter name to search for”);
String searchname = Console.ReadLine();
if (names.Contains(searchname)) // Demonstrate Contains
method works.
{
Console.WriteLine(“Name found”);
}
else
{
Console.WriteLine(“Name not found”);
}
Console.ReadLine();
}
}
}

The code above is fairly self explanatory however perhaps a few parts are worthy of explanation in particular the creation
of the list.


Firstly as we are using System.Collections.Generic we are using a generic List class i.e. this can be a list of any object but
the type must be specified as the list is created.

Free download pdf