atomicgs12
asked on
Need to access variables within C# class
In the code below I want to access hLibModule and listner through out the code within the namespace, MyClass. I am getting "Cannot access a non-static member of outer type MyClass.Program' via nested type MyClass.Program.Local' error as the code stands. Can someone please help?
namespace MyClass
{
public class Program
{
IntPtr hLibModule;
MySecondClass listener;
public class MyLocal
{
public void Init()
{
hLibModule = LoadLibrary("MyDLL.dll");
if (DllRegisterServer() != 0)
{
// MessageBox.Show("Could not initialize the SMSTrap DLL");
}
else
{
listener = new MySecondClass ();
}
}
}
static void Main(string[] args)
{
// start SMS text trapping
MyLocal lcl = new MyLocal ();
lcl.Init();
}
}
namespace MyClass
{
public class Program
{
IntPtr hLibModule;
MySecondClass listener;
public class MyLocal
{
public void Init()
{
hLibModule = LoadLibrary("MyDLL.dll");
if (DllRegisterServer() != 0)
{
// MessageBox.Show("Could not initialize the SMSTrap DLL");
}
else
{
listener = new MySecondClass ();
}
}
}
static void Main(string[] args)
{
// start SMS text trapping
MyLocal lcl = new MyLocal ();
lcl.Init();
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If you want to hide hLibModule from the rest of the app, then the declaration structure is reasonable. In which case simply using
static IntPtr hLibModule;
will work. Watch out for multi-threading though. If more than one thread can access hLibModule and the code it leads to is not re-entrant you will need to put lock statements round the access
static IntPtr hLibModule;
will work. Watch out for multi-threading though. If more than one thread can access hLibModule and the code it leads to is not re-entrant you will need to put lock statements round the access
ASKER
nmarun: - how does 'listener' in Class MyLocal get reconized?
Try using 'out' keyword and pass a type of the MySecondClass to the Init method.
hLibModule = lcl.Init(out listener);
public IntPtr Init(MySecondClass listener)
{
//...
}
Here's more information on the 'out' and 'ref' keywords:
http://geekswithblogs.net/ftom/archive/2008/09/10/c-and-the-difference-between-out-and-ref.aspx
Arun
hLibModule = lcl.Init(out listener);
public IntPtr Init(MySecondClass listener)
{
//...
}
Here's more information on the 'out' and 'ref' keywords:
http://geekswithblogs.net/ftom/archive/2008/09/10/c-and-the-difference-between-out-and-ref.aspx
Arun
Did this work for you?
Arun
Arun
The way I'd write the Init method is that it would return a IntPtr. This way, my code looks lot more cleaner.
Arun
Open in new window