473,805 Members | 1,887 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Global variable question.

I'm switching over from VB and I have a question.

Suppose I had a VB project with 2 forms and one variable. Call them
Form1,Form2 and strUsername. Suppose I want to initialize strUsername
to "jones" and use this value in Form1 and Form2 at any time.

In VB I would create a module with the following code:

Module test
Public strUsername As String
End Module

In my Form1_Load event I would have something like this:

Private Sub Form1_Load
strUsername = "jones"
End Sub

So my question is what would be the best way to do this in C#? I
realize there are no globals so the only thing I can think of doing is
to add a property to Form1 and Form2 called strUsername and set it each
time I activate either Form1 or Form2.

Aug 18 '06 #1
3 2973

cr113 wrote:
I'm switching over from VB and I have a question.

Suppose I had a VB project with 2 forms and one variable. Call them
Form1,Form2 and strUsername. Suppose I want to initialize strUsername
to "jones" and use this value in Form1 and Form2 at any time.

In VB I would create a module with the following code:

Module test
Public strUsername As String
End Module

In my Form1_Load event I would have something like this:

Private Sub Form1_Load
strUsername = "jones"
End Sub

So my question is what would be the best way to do this in C#? I
realize there are no globals so the only thing I can think of doing is
to add a property to Form1 and Form2 called strUsername and set it each
time I activate either Form1 or Form2.
There are "globals" in C#, after a fashion. Now, to my understanding
it's different in ASP.NET (WebForms), but in a WinForms application you
just need to make a class that will contain some global information. In
your example, let's say it's user information. You could make a class
like this:

public class UserInformation
{
private static string _userName = "";

// So that nobody can create an instance... .NET 2.0 has "static
class" for this...
private UserInformation ()
{ }

public static string UserName
{
get { return UserInformation ._userName; }
set
{
if (value == null)
{ this._userName = ""; }
else
{ this._userName = value; }
}
}
}

Now you can say UserInformation .UserName from any class in your
program, and get / set the user name.

Aug 18 '06 #2

Bruce Wood wrote:
cr113 wrote:
I'm switching over from VB and I have a question.

Suppose I had a VB project with 2 forms and one variable. Call them
Form1,Form2 and strUsername. Suppose I want to initialize strUsername
to "jones" and use this value in Form1 and Form2 at any time.

In VB I would create a module with the following code:

Module test
Public strUsername As String
End Module

In my Form1_Load event I would have something like this:

Private Sub Form1_Load
strUsername = "jones"
End Sub

So my question is what would be the best way to do this in C#? I
realize there are no globals so the only thing I can think of doing is
to add a property to Form1 and Form2 called strUsername and set it each
time I activate either Form1 or Form2.

There are "globals" in C#, after a fashion. Now, to my understanding
it's different in ASP.NET (WebForms), but in a WinForms application you
just need to make a class that will contain some global information. In
your example, let's say it's user information. You could make a class
like this:

public class UserInformation
{
private static string _userName = "";

// So that nobody can create an instance... .NET 2.0 has "static
class" for this...
private UserInformation ()
{ }

public static string UserName
{
get { return UserInformation ._userName; }
set
{
if (value == null)
{ this._userName = ""; }
else
{ this._userName = value; }
}
}
}

Now you can say UserInformation .UserName from any class in your
program, and get / set the user name.
Thinking about this some more, I think that it's more likely that in
your program you have something called a "User", and that user has an
attribute, which is "Name". This allows you to add more attributes to
your "User" in the future, rather than creating a bunch of independent
global variables for the same thing. You could modify the code like
this:

public class User
{
private static _currentUser = null;
private string _name;

public User() : this("")
{ }

public User(string name)
{
if (name == null) throw new ArgumentNullExc eption("name");
this._name = name;
}

public string Name
{
get { return this._name; }
set
{
if (value == null)
{ this._name = ""; }
else
{ this._name = value; }
}
}

public static User CurrentUser
{
get
{
if (User._currentU ser == null) User._currentUs er = new
User();
return User._currentUs er;
}
set { User._currentUs er = value; }
}
}

Now you can get the current user's name using

User.CurrentUse r.Name

from any class in your program. You can also create other User
instances with other names, and add more attributes to your User (like
e-mail address, password, whatever) in the future.

Aug 18 '06 #3

Excellent!

Thanks!

Aug 18 '06 #4

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

Similar topics

10
17890
by: Matt | last post by:
Greetings, What are people's thoughts on global variables in C++? Why are we taught not to use them in programming? Is it true that if you are running two copies of the C program one copy can overwrite another copies global variable? I know that you could overwrite a value in a global variable from a function, but you could also do that if you pass the variable in and then out again... so how is that any different?
9
2383
by: Tony Johansson | last post by:
Hello! I know it's bad design to use global variables. I just want to ask a question about them. Is global variables and global static variables the same. These are define outside any function at the top of the a file where you have them. //Tony
7
2691
by: Lyn | last post by:
Hi and Season's Greetings to all. I have a question regarding the use of a qualifier word "Global". I cannot find any reference to this in Access help, nor in books or on the Internet. "Global" seems to be recognised by Access in at least three cases:- 1) "Global Const". Recently someone in this group helped me resolve a problem, and it involved the use of a Global Const. By Googling "Global Const", I got plenty of hits -- but they...
44
2046
by: Mohanasundaram | last post by:
int i = 10; int main() { int i = 20; return 0; } Hi All, I want to access the global variable i inside the main. Is there
24
2533
by: LP | last post by:
After a code review one coworker insisted that global are very dangerous. He didn't really give any solid reasons other than, "performance penalties", "hard to maintain", and "dangerous". I think that I am using them appropriate in class in question. One typical example: This class initiates TCP session, keeps sending commands to the server app and gets messages and codes back, message and code are stored in global variables to be preserved...
44
3651
by: fabio | last post by:
Why? i' ve heard about this, the usage of global vars instead of locals is discouraged, but why? thx :)
37
2753
by: eoindeb | last post by:
Sorry to ask another global variable question, but from reading other posts I'm still not sure whether to use them or not. I have a program with a set function that calls 4 other functions in order - let's say function A, B, C, D. It always calls function A first which is a function that returns a system path. Now all other functions require that variable as well (function A returns a char pointer)
53
26413
by: fdmfdmfdm | last post by:
This is an interview question and I gave out my answer here, could you please check for me? Q. What are the memory allocation for static variable in a function, an automatic variable and global variable? My answer: static variable in function and global variable are allocated in head, and automatic variable is allocated in stack. Right?
9
3039
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
112
5499
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 that may print some messages. foo(...) { if (!silent)
0
9596
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10609
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10360
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10366
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10105
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9185
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
3845
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.