Question: I am having some trouble with assemblies and DLL's.

instrument\_ is declared as an object and I'm creating an instance of "PP150" from the dll whose path is specified by path\_.

```
string className = ContineoProperties.getSingleton().getClassName(path_);
assembly_ = Assembly.LoadFrom(path_);
Type classType = assembly_.GetType("Instrument." + className);
instrument_ = Activator.CreateInstance(classType);

```

Later I to call the method `isntrument_.instrumentCommand(cmd.getCommandName())`

The error I get is with when i call the method.

> 
> 'object' does not contain a definition for 'instrumentCommand'
> 
> 
> 

The isntrument\_ is created fine. its just the method call that's giving me a problem. The method does exist in the "PP150.dll". Do I need some DLLImport to allow it to recognize it as a function? 

Thanks, 
P

Answer: 
If object type is not known in compile time,

To call a method defined on an object, you must use Reflection.

```
MethodInfo mInfo = classType.GetMethod("instrumentCommand");

mInfo.Invoke(instrument_, new Object[] { _parameters});

```
The most simple thing would be to link agains PP150.

If you did link against the dll you must use Assembly.LoadFile or Assembly.Load and not LoadFrom because the last one will cause the assembly load to load your assembly in the LoadFrom loader context which will alter type identity. 
Suppose you load the Type T from Assembly A via LoadFrom and you link against A as well.

```
object CreateTypeFrom()
{
    var A = Assembly.LoadFrom(@"xxxx");
    return A.CreateInstance("T");
}

void Test()
{
    object t = CreateTypeFrom();
    T RealT = new T(); // no prob
    T Castedt = (T)t; // this will throw an InvalidCastException
    T isNull = t as T; // this will result in a null instance
}

```

As you can see although you did create two times an instance of T they cannot be casted to due to different loader context which will make the type pretty useless.

To get rid of these things you could simply use Reflection to create a proxy type which will forward your calls to the proxy type. If you are using .NET 4 you can take advantage of the DLR to find the best matching methods at runtime. The code below creats a Version object and returns it as dynamic object. Then I do call the Major property to an integer and print it out to console. This does work with no exceptions nor compile time errors if you are using .NET 4 or later.

```
        dynamic CreateTypeFrom()
        {
            var assembly = typeof(string).Assembly;
            return assembly.CreateInstance("System.Version", true, BindingFlags.CreateInstance, null, new object[] { 1, 2, 3, 4 }, null, null);
        }

        [TestMethod]
        public void Test()
        {
            var t = CreateTypeFrom();
            int major = t.Major;
            Console.WriteLine(major);
        }

```