0

There is a C#.net library project whose DLL name is customer.dll. It has a class name customer with a function name show(). I want to call this function from another project but don't want to add the reference to the caller project. Can this be done? Is there any C#.net class that can achieve this?

gorkem
  • 731
  • 1
  • 10
  • 17
  • 1
    you can check how to use reflection in c#. assembly load and access the Method create a instances and access the method – umasankar Jul 05 '17 at 06:22
  • 2
    Possible duplicate of [How to use reflection to call method by name](https://stackoverflow.com/questions/3110280/how-to-use-reflection-to-call-method-by-name) – garfbradaz Jul 05 '17 at 06:40

1 Answers1

8

Yes, you can load assemblies dynamically using Assembly.LoadFile

Assembly.LoadFile("c:\\somefolder\\Path\\To\\Code.dll");

You are then going to need to use Reflection to get the methodinfo for the function you want to invoke or use the Dynamic keyword to invoke it.

var externalDll = Assembly.LoadFile("c:\\somefolder\\Customer.dll");
var externalTypeByName = externalDll.GetType("CustomerClassNamespace.Customer");

// If you don't know the full type name, use linq
var externalType = externalDll.ExportedTypes.FirstOrDefault(x => x.Name == "Customer");

//if the method is not static create an instance.
//using dynamic 
dynamic dynamicInstance = Activator.CreateInstance(externalType);
var dynamicResult = dynamicInstance.show();

// or using reflection
var reflectionInstance = Activator.CreateInstance(externalType);
var methodInfo = theType.GetMethod("show");
var result = methodInfo.Invoke(reflectionInstance, null);

// Again you could also use LINQ to get the method
var methodLINQ = externalType.GetMethods().FirstOrDefault(x => x.Name == "show");
var resultLINQ = methodLINQ.Invoke(reflectionInstance, null);
Alexander Higgins
  • 6,765
  • 1
  • 23
  • 41