Vaibhav Srivastava
Vaibhav Srivastava

Reputation: 43

How to invoke c# function from another project without adding reference?

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?

Upvotes: 0

Views: 2397

Answers (1)

Alexander Higgins
Alexander Higgins

Reputation: 6923

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

Upvotes: 8

Related Questions