This is the last topic on variables , I promise!!!!!!!
Today , we shall talk about special type of variables , GLOBAL variables. I put the word global in all caps for a purpose , it is generally ‘understood’ that global variables should be in capitals. Why you may ask. It is to make them different from every other variables. And saying that I realised I have not gone though the lifetime of the variables. Perhaps I should do that now.
Lifetime of a variable , or scope of the variable is basically in the bracket , to be more precise , curly brackets. Here is one example ,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Variables
{
class Program
{
public static String testString1 = "test1";
static void Main(string[] args)
{
String testString1 = "test2";
Console.WriteLine(testString1);
printTest();
}
public static void printTest()
{
Console.WriteLine(testString1);
}
}
}
If you were to run this C# program in Visual Studio, you would have gotten this result ,
test2
test1
Press any key to continue ....
The thing to take note is of the output of the variable testString1 , which prints out as “test1″ even after it has been changed to “test2″. This is mainly due to the fact that the variable testString1 in the Main function , I have not been to functions too I know , is a local variable. Meaning once the function ends , so is its life. Btw , to create global variables in C# , you would need to create a static class first then a static method.
To use the variable everywhere ,
StaticClass.StaticVar = "Some value";
It is much simpler in C/C++/Java though. But I think you get the drift. Ok , so why need such variable that is available to all files/classes/functions in the project? One of the main reason is to standardization.
Suppose you are doing a math program/website , and you will need a variable for the value of pi. It is possible to declare it everywhere you need it , “float pi = 3.14;”. But what if later you are told more precision is needed? Then are you going to go through the files one by one and change each pi variables? Another example would be school grades , for a school website. It is obvious that highest grade/mark is 100. You might be tempted to it everywhere. Then the school change to 110 marks as the highest mark. Then what are you going to do??
As you can see from the above examples , for values that would be standardized everywhere , it is much more efficient and easier to put them in one place and only at one place. Easy to change now and later as well.
Hope this has given you some thoughts. Thanks for reading. Cya!