jmc
jmc

Reputation: 1729

Cast object to unknown type

I would like to create a dynamic method that populates a dropdownlist with any object based on the parameters. Here's my code:

PopulateDropDownList(ddl, GetList(), typeof(MyClass));

public void PopulateDropDownList(DropDownList ddl, IEnumerable list, Type type)
{
    object obj = Activator.CreateInstance(type);
    foreach (var item in list)
        ddl.Items.Add(new ListItem(((obj)item).Name, ((obj)item).ID.ToString()));
}

Basically, what I want to do is to cast Name and ID to a type but I'm getting an error when I compile.

Upvotes: 0

Views: 1000

Answers (1)

hazzik
hazzik

Reputation: 13344

You can use dynamic keyword, assuming you are running .NET 4 or above

public void PopulateDropDownList(DropDownList ddl, IEnumerable list, Type type)
{
    foreach (var item in list)
        ddl.Items.Add(new ListItem(((dynamic)item).Name, ((dynamic)item).ID.ToString()));
}

Or, (if) you can use generic version and pass accessors to get the key and value.

public void PopulateDropDownList<T>(DropDownList ddl, IEnumerable list, Func<T, string> key, Func<T, string> value)
{
    foreach (T item in list)
        ddl.Items.Add(new ListItem(key(item), value(item));
}

PopulateDropDownList<MyClass>(ddl, GetList(), x => x.Name, x => x.ID.ToString());

Or, at least, you can use reflection, to get required properties.

Upvotes: 3

Related Questions