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.