Search code examples
c#genericsreflectionvalueinjecter

Moving from legacy to ValueInjecter


We had a custom object extension method that would handle the following.

  • Source is DataRow target is class.
  • Source is DataTable target is a List<class>
  • Source is class target is class
  • Source is List<class> target is List<class>

I found ValueInjecter and DataTable so I can handle a DataRow and DataTable.
So I am to the step where I am gluing it all together.

Here is what I tried.

public static class ObjectExtensions
{
    public static void OldFill(this object fillMe, object sourceObject)
    {
        Type sourceType = sourceObject.GetType();
        Type fillType = fillMe.GetType();

        switch (sourceType.Name)
        {
            case "DataRow":
                fillMe.InjectFrom<DataRowInjection>(sourceObject);
                break;

            case "DataTable":
                fillMe.InjectFrom<DataTableInjection<fillType>>(sourceObject);
                break;

            default:
                fillMe.InjectFrom(sourceObject);
                break;
        }
    }
}

Not sure how to get the right fillType to make the code work right.
Because this is legacy code I do not want to change the extension signature.


Solution

  • I don't know the answer, but I can say DataTableInjection<fillType> won't compile. You'd need to use Reflection to do the binding, something like this:

    case "DataTable":
      var tableInjector = typeof (DataTableInjection<>).MakeGenericType(fillType);
      tableInjector.GetMethod("InjectFrom").MakeGenericMethod(tableInjector)
        .Invoke(fillMe, new[] { sourceObject });
      break;