using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication
{
interface IReadOnlyList</*out*/ T> : IEnumerable<T>
{
int Count { get; }
T this[int index] { get; }
}
interface IList<T> : IReadOnlyList<T>
{
new int Count { get; }//Note: new
new T this[int index] { get; set; }//Note: new
void Add(T item);
}
class List<T> : IList<T>
{
private readonly System.Collections.Generic.IList<T> _innerList;
public List(System.Collections.Generic.IList<T> innerList)
{
if (innerList == null) throw new ArgumentNullException("innerList");
_innerList = innerList;
}
public int Count
{
get { return _innerList.Count; }
}
public T this[int index]
{
get { return _innerList[index]; }
set { _innerList[index] = value; }
}
public void Add(T item)
{
_innerList.Add(item);
}
public IEnumerator<T> GetEnumerator()
{
return _innerList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
class Program
{
static void SomeMethod(IReadOnlyList<int> lst)
{
Console.WriteLine("Count from IReadOnlyList: {0}", lst.Count);
Console.WriteLine("First item from IReadOnlyList: {0}", lst[0]);
foreach (var i in lst)
Console.WriteLine(i);
}
static void SomeMethodUsingReflection(object obj)
{
var iface = obj.GetType().GetInterfaces()
.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof (IList<>));
if (iface != null)
{
var countProp = iface.GetProperty("Count");
var count = (int)countProp.GetValue(obj, null);
Console.WriteLine("Count using reflection: {0}", count);
}
}
static void MyMethod(IList<int> lst)
{
lst.Add(10);
lst.Add(20);
lst.Add(30);
lst[0] = 40;
Console.WriteLine("Count from IList: {0}", lst.Count);
Console.WriteLine("First item from IList: {0}", lst[0]);
SomeMethod(lst);
SomeMethodUsingReflection(lst);
}
static void Main()
{
var lst = new List<int>(new[] {1, 2, 3}.ToList());
MyMethod(lst);
//Console.ReadKey();
}
}
}