Can Not Access Static Class Function?

Here is my Code

static class NativeMethods
{

    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string dllToLoad);    
    [DllImport("kernel32.dll")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
    [DllImport("kernel32.dll")]
    public static extern bool FreeLibrary(IntPtr hModule);
}
class manageCAN
{
    // Getting the String for .dll Address
    string dllfile = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\VTC1010_CAN_Bus.dll";
    // Loading dll using Native Methods
    IntPtr pDll = NativeMethods.LoadLibrary(dllfile);
}

I get an error: Error 1 A field initializer cannot reference the non-static field, method, or property 'manageDLL.manageCAN.dllfile'

Please suggest a solution. Why can't I initialize my variable "pDll"?

Jon Skeet
people
quotationmark

Why can't I initialize my variable "pDll"?

The compiler is telling you exactly why - you can't access instance fields within an instance field initializer. It looks like these should probably be static anyway:

static readonly string dllfile = ...;
static readonly IntPtr pDll = NativeMethods.LoadLibrary(dllfile);

But if you really want them to be instance fields, you'll need to initialize pDll in the constructor:

class manageCAN
{
    // Getting the String for .dll Address
    string dllfile = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\VTC1010_CAN_Bus.dll";
    // Loading dll using Native Methods
    IntPtr pDll;

    public manageCAN()
    {
        pDll = NativeMethods.LoadLibrary(dllfile);
    }
}

people

See more on this question at Stackoverflow