Search code examples
c#genericsfilehelpers

Passing Dynamic Loaded Type to SomeFunction<T>


I am trying to pass the type of a dynamically loaded dll (it uses an interface, but I need the conectrete implementation of this) to a function and am missing something.

var data = LoadAssemblyFromParamenter(pathToDataDll);
Type dataType = data.GetType().MakeGenericType(data.GetType());
SomeTest<dataType>();

public void SomeTest<T>() 
{
    //do something with T 
}

Error is "The Type or Namespace 'dataType' coulnd not be found..."

The concrete type is for a FileHelpers object (that uses fields), so I need the concrete implmentation.

p.s. This has to be .net 3.5 ....

To elaborate SomeMethod<T>( IEnumerable<T> items ) calls

public static void WriteRecords<T>(IEnumerable<T> records, string fileName )
    where T: ICMSDataDictionary
{
    if (records == null || String.IsNullOrEmpty(fileName))
        return;

    if (records.Any())
    {
        FileHelpers.DelimitedFileEngine<T> engine =
            new FileHelpers.DelimitedFileEngine<T>();
        engine.WriteFile(fileName, records);
    }
}

Solution

  • Use the "dynamic" keyword:

    public void Doit() {
      dynamic data=LoadAssemblyFromParamenter(pathToDataDll);
      SomeTest(data);
    }
    
    public void SomeTest<T>(T arg) {
      Debug.WriteLine("typeof(T) is "+typeof(T));
    }
    

    !!!EDIT!!!: sorry, I missed that you needed the 3.5 Framework. If so, use this:

    public void Doit() {
      var data=LoadAssemblyFromParamenter(pathToDataDll);
      var mi=this.GetType().GetMethod("SomeTest").MakeGenericMethod(data.GetType());
      mi.Invoke(this, new object[0]);
    }
    
    public void SomeTest<T>() {
      Debug.WriteLine("typeof(T) is "+typeof(T));
    }