G.Esmeijer said:
Hi,
I would like to use a couple of hundred constant string variable throught my
program. I want to use them from every corner of the software. In Vb I jst
declared the global and it worked . How do I perform this in C#?
The idea of global variables is frowned upon in object oriented
programming languages. In cases like this, one solution is to declare
them as members of a class:
class MyClass
{
public const String FOOBAR = "FooBar";
public static String GOOBER = "Goober";
}
The class need not contain only string constants, and can also include
code if it is related to the constants.
In C#, a const variable is implicitly declared as static, so you would
probably prefer the first example, ie FOOBAR.
You must always reference FOOBAR like this:
String MyString = MyClass.FOOBAR;
You can't do this:
MyClass myClass = new MyClass;
String foobar = myClass.FOOBAR;
Static members must be referenced through the type name such as MyClass.
They can't be accessed through a class instance such as myClass. This is
true of both FOOBAR and GOOBER, since they are both static, even though
FOOBAR is made static only implicitly.
The key thing to grasp here is that you are using MyClass as a way of
organizing your code. As a result, you may find that of your hundreds of
String constants, some belong in a class called MyPurchaseOrderData and
another while others belong in a class called MyPayrollData. The point
is to give the classes meaningful names.
By the way, a name like NE_01_001 can, in some cases, be dangerous. You
want to try to give variables meaningful names, such as
NORTH_EAST_SECTOR_01.
- Charlie