General method to add any entity to its entity list

General method to add any entity to its entity list

Post by Andru » Tue, 25 Sep 2007 06:50:00


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 ?

Andrus.


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>();
}
}
 
 
 

General method to add any entity to its entity list

Post by Nicholas P » Wed, 26 Sep 2007 01:17:56

Andrus,

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
reflection.


--
- Nicholas Paldino [.NET/C# MVP]
- XXXX@XXXXX.COM