.net runtime type casting when using reflection

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2010-06-07T13:15:31Z Indexed on 2010/06/07 13:22 UTC
Read the original article Hit count: 295

Filed under:
|
|
|

I have need to cast a generic list of a concrete type to a generic list of an interface that the concrete types implement. This interface list is a property on an object and I am assigning the value using reflection. I only know the value at runtime. Below is a simple code example of what I am trying to accomplish:

public void EmployeeTest()
    {
        IList<Employee> initialStaff = new List<Employee> { new Employee("John Smith"), new Employee("Jane Doe") };
        Company testCompany = new Company("Acme Inc");
        //testCompany.Staff = initialStaff;

        PropertyInfo staffProperty = testCompany.GetType().GetProperty("Staff");
        staffProperty.SetValue(testCompany, (staffProperty.PropertyType)initialStaff, null);
    }

Classes are defined like so:

public class Company
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    private IList<IEmployee> _staff;

    public IList<IEmployee> Staff
    {
        get { return _staff; }
        set { _staff = value; }
    }

    public Company(string name)
    {
        _name = name;
    }
}

public class Employee : IEmployee
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public Employee(string name)
    {
        _name = name;
    }
}

public interface IEmployee
{
    string Name { get; set; }
}

Any thoughts?

I am using .NET 4.0. Would the new covariant or contravariant features help?

Thanks in advance.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about generics