Newbie question: Public variables

  • Thread starter Thread starter Tobias Froehlich
  • Start date Start date
T

Tobias Froehlich

Hi,

Can anyone tell me how I can create a variable (or an integer array to
be exact) that is public within all the project files? I know that by
standard a variable inside a function does not exist outside of that
function. But is there a way to make my variable public?
 
You must create a global class, then you declare your variable as static. In
this way you can use your variable anyplace in your project.

Regards,
 
Tobias,

You will want to create a static member of a type. Then, once you have
that member exposed (because it is public), any code can access it in the
same app-domain. For example:

public class MyClass
{
public static int MyInt = 2;
}

You can then access the value using "MyClass.MyInt".

Hope this helps.
 
Thus spake Tobias Froehlich:
Hi,

Can anyone tell me how I can create a variable (or an integer array to
be exact) that is public within all the project files? I know that by
standard a variable inside a function does not exist outside of that
function. But is there a way to make my variable public?

In VB.NET you could use a module. In C#, create a static property in one
of your classes.
 
You can declare it at the namespace level, or you could create a static
property in a given class and everything will be able to access it.
 
Hello Tobias,

I don't think you can place an int[] outside a class definition,
however you can create a Constants class that declares only static
variables, that you then can access.

Best regards, Wouter

namespace Test
{
public class Constants
{
public static int[] myInts = {1,2,3,4};
}

public class Entry
{
// Do some things with int[]
foreach(int i in Constants.myInts)
{
Console.WriteLine(i.ToString());
}
Constants.myInts[0] = 5;
foreach(int i in Constants.myInts)
{
Console.WriteLine(i.ToString());
}
}
}
 
You can declare it at the namespace level


No you can not. At the namespace level you may declare
classes, delegates, enums, interfaces or structs.
Nothing more, nothing less.


And why is everybody giving the same answer 5 times
over to a post that already has been answered??
Seems like a wast of time.

Oh well,

Bst rgrds, Wouter van Vugt
 
Back
Top