Click here to Skip to main content
15,913,181 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I would like to initialize a global variable inside a class during run time..is it possible?Any other way?

i.e console.writeline("Enter the path")

string path=console.readline();

Right now I have initialized only main method it works..however i have couple of other methods where this variable "path" should be used

What I have tried:

Tried placing out side the main method
declared the variable as static .. during execution it returns null
Posted
Updated 26-Jul-16 22:25pm

1 solution

There are a couple of problems here: first off C# doesn;t have global variables: everything is within a class. The closest you can get is to have a static variable inside a class and that will be available to the whole code via the class name:
C#
public class MyClass
   {
   public static int globalValue = 666;
   ...
   }
...
public class MyOtherclass
   {
   private void MyMethod()
      {
      Console.WriteLine(MyClass.globalValue);
      }
   }

When you do that, you can use a static constructor for MyClass to initialize the variable:
C#
public class MyClass
    {
    public static string globalValue;
    static MyClass()
        {
        globalValue = File.ReadAllText(@"D:\Test Data\Primes.txt");
        }
    }
The static constructor will be called before the variable is used.
 
Share this answer
 
Comments
ShaHam11 27-Jul-16 6:37am    
thanks OrginialGriff.. Today i understood why actually we have static constructor.. earlier I came upto declaring static variable..but totally forgot that I need to initialize this variable in static constructor... thans for the help and support
OriginalGriff 27-Jul-16 6:45am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900