blah blah blah is here! blah blah » Close

up0down
link

Hi,
I have made a class called Globals. I am declaring few variables to use them throughout my solution.
Following is the class:
public class Globals
{
public static PCOMMSERVERLib.PDeviceClass Turbo;
public static int device_number;
string command;
}
PCOMMSERVERLIB has already been added under references so all the COM libraries are included. I have created an instance of PDeviceClass called "Turbo".
In order to access the COM libraries I wrote:
Globals.Turbo.Open(Globals.device_number, out Success);
It is giving me the following error:
Object reference not set to an instance of an object.
I had also checked to see if the error goes by declaring an object for class Globals. It does not work.
Any suggestions?

last answered 2 years ago

1 answers

up0down
link

Try changing this line:
public static PCOMMSERVERLib.PDeviceClass Turbo;
to:
public static PCOMMSERVERLib.PDeviceClass Turbo = new PCOMMSERVERLib.PDeviceClass();

up0down
link

I already had this on top of the file as:
PDeviceClass Turbo = new PDeviceClass();
It is still pointing to the line:
Globals.Turbo.Open(Globals.device_number, out Success);

up0down
link

Hi Vulpes,
It's working now. I was declaring the object out of the global class!
Thanks!

up0down
link

Hi,
If I have a method called Turbo.GetResponse(int dwDevice, string question, bool bAddLF, out string pAnswer, out int pstatus);
And I declare each of these variables as separate names in my Globals class, can I access them using Globals.Turbo.GetResponse(Globals.device_number, Globals.command, Globals.false, out Globals.response, out Globals.status)

up0down
link

Yes, you could store those static variables in your Global class as well.
Notice though that Globals.false wouldn't be allowed as 'false' is a keyword. You could, however, use Globals.False instead.

up0down
link

I am unable to access string variables from my Globals. It only shows Globals.device_number.
I have even made my string variables public. Still cannot access them in the solution.

up0down
link

string command;
should be:
public static string command;
I'd also make Globals into a static class so that you don't inadvertently add any instance variables.

up0down
link

Hi,
What is the reason that I need to declare these variables as static?
Regards,
AVM

up0down
link

It's best to make them static so you don't have to create an instance of the Global class to access them - you can just prefix them with the class name.
Global variables are in any case naturally static because they have the same value throughout the application.
Making the class into a static class ensures that you can't create an instance of it as all members must then be static.

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback