General method to add any entity to its entity list



I'm creating ComboBox class which uses entity list as datasource where
entity class name is passed as string. Entity list is filled dynamically at
run time.

So need to add entities of different types to corresponding entity lists.
I created general Add() method for this.

This method call causes exception from my code
"List does not have Add method"

How to fix ?


using System.Collections.Generic;
using System;
using System.Reflection;

class TestApplication {

static void Main() {
object customerList = Customer.GetEmptyList();
Add(customerList, new Customer());

// General routine to add entity to its corresponding list.
static void Add(object entityList, object entity) {

Type type = entityList.GetType();
Type[] types = new Type[1];
types[0] = entity.GetType();

MethodInfo methodInfo = type.GetMethod("Add",
BindingFlags.Public, null, types, null);
if (methodInfo == null)
// how to fix code so that this exception does not occur ?
throw new ApplicationException("List does not have Add method");

object[] parameters = new object[1];
parameters[0] = entity;
methodInfo.Invoke(entityList, parameters);

class Customer : ActiveRecordBase<Customer> {}

public class ActiveRecordBase<T> {

public static List<T> GetEmptyList() {
return new List<T>();



Nicholas Paldino [.NET/C# MVP]


From what it seems, you need to add the Instance binding flag to the
Public binding flag to get the method.

I would recommend using an interface instead which will have the add
method on it, and then you can pass implementations of that list to your
method to add a new instance. It would be much better than using

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question