Thursday, October 8, 2009

C# Readonly List

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ListReadOnly
{
class Program
{
static void Main(string[] args)
{
Patterns p = new Patterns();
IList lstAlphabets = p.GetAlphabetList();
p.AddAlphabetToList("D");
foreach (string s in lstAlphabets)
{
Console.WriteLine(s);
}
try
{
foreach (string s in lstAlphabets)
{
//This line of code should throw error.
lstAlphabets.Add("P");
Console.WriteLine(s);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
class Patterns
{
List m_lNames = new List { "A", "B", "C" };
public IList GetAlphabetList()
{
return m_lNames.AsReadOnly();
}
public void AddAlphabetToList(string s)
{
m_lNames.Add(s);
}
}
}

Output:


No comments: