473,385 Members | 1,872 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

global variable?

Hi,

How can I define a global variable in .NET? I mean, everywhere in the same
project can access this variable.

Thanks
Nhan
Nov 16 '05 #1
13 6974
Le, Thanh-Nhan wrote:
Hi,

How can I define a global variable in .NET? I mean, everywhere in the same
project can access this variable.

Thanks
Nhan


You can't have a global variable in terms of procedural/modular
programming, because in C# all funcs/props/fields/whatever have to be
wrapped inside a class.

So you can declare a static variable in one of your classes in the project:

class Class1
{
...
public static int i = 0;
...
}

and then access it like this: Class1.i = 3

Hope it helps
Andrey
Nov 16 '05 #2
Well, you can do it with a static variable but just because you can doesn't
mean you should.

C# doesn't provide for global variables for a very good reason. They are
architecturally unsound and promote bad programming practices. You should
really find another way.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Le, Thanh-Nhan" <le*****@freenet.de> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
Hi,

How can I define a global variable in .NET? I mean, everywhere in the same
project can access this variable.

Thanks
Nhan

Nov 16 '05 #3
Nhan,

You can declare a variable as static. Once you do that, depending on
the accessibility level, you can access it everywhere. If you declare it as
public static, then any assembly referencing your assembly can see the
field. If it is internal static, then only types in your assembly can
reference it. If it is protected static, then only your type, and any type
deriving from your type can access it.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Le, Thanh-Nhan" <le*****@freenet.de> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
Hi,

How can I define a global variable in .NET? I mean, everywhere in the same
project can access this variable.

Thanks
Nhan

Nov 16 '05 #4
OK, thanks

"MuZZy" <le*******@yahoo.com> schrieb im Newsbeitrag
news:RY********************@rcn.net...
Le, Thanh-Nhan wrote:
Hi,

How can I define a global variable in .NET? I mean, everywhere in the same project can access this variable.

Thanks
Nhan

You can't have a global variable in terms of procedural/modular
programming, because in C# all funcs/props/fields/whatever have to be
wrapped inside a class.

So you can declare a static variable in one of your classes in the

project:
class Class1
{
...
public static int i = 0;
...
}

and then access it like this: Class1.i = 3

Hope it helps
Andrey

Nov 16 '05 #5
OK, thanks

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> schrieb
im Newsbeitrag news:uq**************@TK2MSFTNGP11.phx.gbl...
Nhan,

You can declare a variable as static. Once you do that, depending on
the accessibility level, you can access it everywhere. If you declare it as public static, then any assembly referencing your assembly can see the
field. If it is internal static, then only types in your assembly can
reference it. If it is protected static, then only your type, and any type deriving from your type can access it.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Le, Thanh-Nhan" <le*****@freenet.de> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
Hi,

How can I define a global variable in .NET? I mean, everywhere in the same project can access this variable.

Thanks
Nhan


Nov 16 '05 #6
OK, thanks.

But can you tell me, which reason? My project need only one variable for an
inform, this variable (or object) will be initialized (or set) only once.
What can I do, instead?

Nhan

"Bob Powell [MVP]" <bob@_spamkiller_bobpowell.net> schrieb im Newsbeitrag
news:u1**************@TK2MSFTNGP12.phx.gbl...
Well, you can do it with a static variable but just because you can doesn't mean you should.

C# doesn't provide for global variables for a very good reason. They are
architecturally unsound and promote bad programming practices. You should
really find another way.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Le, Thanh-Nhan" <le*****@freenet.de> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
Hi,

How can I define a global variable in .NET? I mean, everywhere in the same project can access this variable.

Thanks
Nhan


Nov 16 '05 #7
Your only other option for this type of situation is to use the
Singleton design pattern. In other words, make it an object instance,
not a static, but make only one of them.
However, depending upon what you need, a Singleton may be overkill.

Nov 16 '05 #8

"Le, Thanh-Nhan" <le*****@freenet.de> wrote in message
news:uR**************@tk2msftngp13.phx.gbl...
OK, thanks.

But can you tell me, which reason? My project need only one variable for
an
inform, this variable (or object) will be initialized (or set) only once.
What can I do, instead?


The problem is that with a simple global variable:

public static int i;

there's no way to enforce that it's only set once. Any code that can read
it also has the privilege to write it, and if it gets reset there is no way
to narrow down who's resetting it. There are many other constructs you can
use, but the simplest is to use a property instead of a variable, which
allows you to do something like:

private static _i;
private static bool _iIsSet = false;
public static int i
{
get { if (!iIsSet)
throw new Exception("i is unset!");
return _i;}
set { if (_iIsSet)
throw new Exception("attempt to reset i!");
_i = value; _iIsSet = true;}
}

This gives the same access to the client code while giving you the ability
to control write access.
Nov 16 '05 #9
That is not my problem. My global variable can be changed, it is no
constants. For example, an option variable, my project need this var, but
when the users change this option, this var will be changed.

But I have another question:
Can I define a constant with "readonly", but the value will be set once
(only once), later? In Java we can do so. As following:

public static readonly int gc_iOption;
public void startup()
{
gc_iOption = 1;
}

Nhan
"Mike Schilling" <ms*************@hotmail.com> schrieb im Newsbeitrag
news:uU**************@TK2MSFTNGP10.phx.gbl...

"Le, Thanh-Nhan" <le*****@freenet.de> wrote in message
news:uR**************@tk2msftngp13.phx.gbl...
OK, thanks.

But can you tell me, which reason? My project need only one variable for
an
inform, this variable (or object) will be initialized (or set) only once. What can I do, instead?

The problem is that with a simple global variable:

public static int i;

there's no way to enforce that it's only set once. Any code that can read
it also has the privilege to write it, and if it gets reset there is no

way to narrow down who's resetting it. There are many other constructs you can use, but the simplest is to use a property instead of a variable, which
allows you to do something like:

private static _i;
private static bool _iIsSet = false;
public static int i
{
get { if (!iIsSet)
throw new Exception("i is unset!");
return _i;}
set { if (_iIsSet)
throw new Exception("attempt to reset i!");
_i = value; _iIsSet = true;}
}

This gives the same access to the client code while giving you the ability
to control write access.

Nov 16 '05 #10
Le, Thanh-Nhan <le*****@freenet.de> wrote:
That is not my problem. My global variable can be changed, it is no
constants. For example, an option variable, my project need this var, but
when the users change this option, this var will be changed.

But I have another question:
Can I define a constant with "readonly", but the value will be set once
(only once), later? In Java we can do so. As following:

public static readonly int gc_iOption;
public void startup()
{
gc_iOption = 1;
}


No, you can't do that in either C# *or* Java. Try compiling the code
above in Java (except using "final" instead of "readonly", as
"readonly" isn't a modifier in Java). You'll get a compiler error:

Test.java:10: cannot assign a value to final variable gc_iOption
gc_iOption = 1;

(It's funny - I think this is the third post in a couple of days
claiming that Java can do something which it can't...)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #11
Hi,
I have tried it.

I declare a readonly variable. Then in static contructor I set the value. It
does. The compiler show me this: it tell, I can do this, but only in a
static constructor.

Thanks
Nhan
"Jon Skeet [C# MVP]" <sk***@pobox.com> schrieb im Newsbeitrag
news:MP************************@msnews.microsoft.c om...
Le, Thanh-Nhan <le*****@freenet.de> wrote:
That is not my problem. My global variable can be changed, it is no
constants. For example, an option variable, my project need this var, but when the users change this option, this var will be changed.

But I have another question:
Can I define a constant with "readonly", but the value will be set once
(only once), later? In Java we can do so. As following:

public static readonly int gc_iOption;
public void startup()
{
gc_iOption = 1;
}


No, you can't do that in either C# *or* Java. Try compiling the code
above in Java (except using "final" instead of "readonly", as
"readonly" isn't a modifier in Java). You'll get a compiler error:

Test.java:10: cannot assign a value to final variable gc_iOption
gc_iOption = 1;

(It's funny - I think this is the third post in a couple of days
claiming that Java can do something which it can't...)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #12
Le, Thanh-Nhan <le*****@freenet.de> wrote:
I have tried it.
Just not with the code you actually posted...
I declare a readonly variable. Then in static contructor I set the
value. It does. The compiler show me this: it tell, I can do this,
but only in a static constructor.


Indeed. That's because the static constructor is guaranteed to run only
once, and before the variable is accessed (with a bit of hand-waving
for special cases).

The same is true in C# - you can set a readonly variable in a
constructor or static constructor (depending on whether it's an
instance variable or a static variable) but not in a normal method.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #13

"Le, Thanh-Nhan" <le*****@freenet.de> wrote in message
news:um**************@TK2MSFTNGP11.phx.gbl...
That is not my problem. My global variable can be changed, it is no
constants. For example, an option variable, my project need this var, but
when the users change this option, this var will be changed.


Regardless, if you want to control (or be able to debug) where the value is
changed, you'll want a property, not a field.
Nov 16 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: David Hitillambeau | last post by:
Hi guys, As I am new to Python, i was wondering how to declare and use global variables. Suppose i have the following structure in the same module (same file): def foo: <instructions>...
4
by: Andrew V. Romero | last post by:
I have been working on a function which makes it easier for me to pull variables from the URL. So far I have: <script language="JavaScript"> var variablesInUrl; var vArray = new Array(); ...
4
by: Dan Elliott | last post by:
Hello, Converting from a working C program to C++, I run into the following error: I have a header: (header.h) namespace shared{ ... struct X{ ...
2
by: Thomas Matthews | last post by:
Hi, I'm getting linking errors when I declare a variable in the global scope, but not inside a function. The declarations are the same (only the names have been changed...). class Book {...
8
by: lawrence | last post by:
I'm learning Javascript. I downloaded a script for study. Please tell me how the variable "loop" can have scope in the first function when it is altered in the second function? It is not defined...
17
by: MLH | last post by:
A97 Topic: If there is a way to preserve the values assigned to global variables when an untrapped runtime error occurs? I don't think there is, but I thought I'd ask. During development, I'm...
10
by: Charles O'Flynn | last post by:
As a complete newcomer (2-3 days) to PHP, although not to programming in general, I have 'dived in' to start a small project to read and parse an XML data stream. I have already worked out most of...
9
by: Ed Jensen | last post by:
I'm having a vexing problem with global variables in Python. Please consider the following Python code: #! /usr/bin/env python def tiny(): bar = for tmp in foo: bar.append(tmp) foo = bar
1
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have...
112
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.