Sunday, 18 August 2013

How to use generic delegates in C#

How to use generic delegates in C#

I have these classes:
public interface IPerson
{
string Name { get; set; }
}
public class Person : IPerson
{
public string Name { get; set; }
}
public interface IRoom
{
List<Furniture> Furnitures { get; set; }
List<Person> People { get; set; }
}
public class Room : IRoom
{
public List<Furniture> Furnitures { get; set; }
public List<Person> People { get; set; }
}
public enum Furniture
{
Table,
Chair
}



And I have this extension method:
public static void Assign<T>(this IRoom sender, Func<IRoom,ICollection<T>>
property, T value)
{
// How do I actually add a Chair to the List<Furniture>?
}



And I want to use it like this:
var room = new Room();
room.Assign(x => x.Furnitures, Furniture.Chair);
room.Assign(x => x.People, new Person() { Name = "Joe" });
But I have no idea how to add T to ICollection.
Trying to learn generics and delegates. I know
room.Furnitures.Add(Furniture.Chair) works better :)

No comments:

Post a Comment