C# – how to import a class from dll

cdlldllimport

mydll.dll

namespace mydll
{
    public class MyClass {
        public static int Add(int x, int y)
        {
            return x +y;
        }
    }
}

In another project how can I import MyClass or just Add function?

I want to add with DllImport,

[DllImport("mydll.dll", CharSet =
CharSet.Auto) ] public static extern
…….

how can I do that?

Best Answer

DllImport is used to call unmanaged code. The MyClass class you have shown is managed code and in order to call it in another assembly you simply add reference to the assembly containing it and invoke the method. For example:

using System;
using mydll;

class Program
{
    static void Main()
    {
        int result = MyClass.Add(1, 3);
        Console.WriteLine(result);
    }
}