0% found this document useful (0 votes)
226 views3 pages

C# Global Variable

1) The document discusses global variables in C#, including defining a public static class to contain global variables and constants. It provides an example using a global string constant, integer property with get/set accessors, and boolean field. 2) Global variables can cause problems with threading and debugging if not used carefully. It is better to access global variables through access routines/properties rather than public fields to avoid issues. 3) The document emphasizes that global variables are best used with access routines/properties for abstraction and locking in multithreaded applications. It provides tips for effective use of global variables in C#.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
226 views3 pages

C# Global Variable

1) The document discusses global variables in C#, including defining a public static class to contain global variables and constants. It provides an example using a global string constant, integer property with get/set accessors, and boolean field. 2) Global variables can cause problems with threading and debugging if not used carefully. It is better to access global variables through access routines/properties rather than public fields to avoid issues. 3) The document emphasizes that global variables are best used with access routines/properties for abstraction and locking in multithreaded applications. It provides tips for effective use of global variables in C#.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

18/2/2015

C#GlobalVariable

C#GlobalVariable

Go

C# : .NET : Method

Globalvariablesareuseful.Buttheycan
leadtocertainproblemsthatarehardto
debug.Globalvariablescancausecertain
problemsinsoftwaredevelopment.But
manyprogramscanbenefitfromthemif
usedinacontrolledmanner.

Example
ThestatickeywordintheC#language
describesamembersuchasafield,propertyormethodthatispartof
atype,notaninstanceofthetype.Thestatickeywordwasmainly
chosenforhistoricalreasonsasitwasusedinCandC++.
Static
Next:
Weseetwofiles:afilethatcontainstheglobalvariablesina
publicstaticclass,andProgram.cs,whichusestheglobalclass.
Globalvariablesclass,GlobalVar.cs:C#
///<summary>
///Containsglobalvariablesforproject.
///</summary>
publicstaticclassGlobalVar
{
///<summary>
///Globalvariablethatisconstant.
///</summary>
publicconststringGlobalString="ImportantText";
///<summary>
///Staticvalueprotectedbyaccessroutine.
///</summary>
staticint_globalValue;
///<summary>
///Accessroutineforglobalvariable.
///</summary>
publicstaticintGlobalValue
{

get

return_globalValue;

set

_globalValue=value;

}
}
///<summary>
///Globalstaticfield.
///</summary>
publicstaticboolGlobalBoolean;
}
C#programthatusesglobalvariables,Program.cs
usingSystem;
classProgram
http://www.dotnetperls.com/globalvariable

1/3

18/2/2015

C#GlobalVariable

{
staticvoidMain()
{

//Writeglobalconstantstring.

Console.WriteLine(GlobalVar.GlobalString);

//Setglobalinteger.
GlobalVar.GlobalValue=400;

//Setglobalboolean.
GlobalVar.GlobalBoolean=true;

}
}

//Writethetwopreviousvalues.
Console.WriteLine(GlobalVar.GlobalValue);
Console.WriteLine(GlobalVar.GlobalBoolean);

Output
ImportantText
400
True

Thepublicconststringwiththe
identifierGlobalStringisanexcellentuse
ofaglobalvariable.Thisfieldisconstant.
Youmustassignitsvalueinlinewithitsdeclarationattheclass
declarationspace.
Tip:
Thepublicaccessmodifieronthefieldmakesitaccessible
throughoutyourprogram.
TheGlobalValuememberisafunctiontype
containingapropertygetaccessorandsetaccessor.
Thisisanaccessroutineofabackingstore.Thebacking
storeisareferencefieldoftypeint.
Note:
The_globalValuefieldismodifiedthroughthesetaccessor.Itis
accessedthroughthegetaccessor.
Property
Globalfield.Finally,theglobalvariable
classcontainsaglobalfieldofBoolean
type.ThebooltypeintheC#language
aliasestheSystem.Booleantype,which
inheritsfromtheSystem.ValueTypestruct.
Tip:
Thisboolfieldcouldcauseproblemsinyourprogrambecauseit
doesnotuseanaccessroutine.

Accessroutines
Expertsinsoftwaredevelopmentconsiderglobalvariablestobeused
mosteffectivelywhenaccessedthroughspecialmethodscalledaccess
routines.Youcanuseaccessroutinesinnearlyanyprogramming
language.
http://www.dotnetperls.com/globalvariable

2/3

18/2/2015

C#GlobalVariable

Tip:
Thesemethodsprovideanotherlayer
ofabstractionoverhowyouusethe
globalvariables.
And:
Intheexample,theproperty
accessor(get)isanaccessor
routine.PleaseseeCodeComplete
bySteveMcConnell,page340.

Threads
GlobalvariablesandstaticvariablesinC#
programscanintroduceproblemswhen
usingmultithreading,whichisused
extensivelyinmanyASP.NETwebsites.An
accessroutinecouldprovidelockingusingthelockstatement.
GlobalVariables
Lock
Also:
ThisisaprobleminmanyWindowsFormsapplicationsthatuse
BackgroundWorkerthreads.
BackgroundWorker

Summary
Weusedglobalvariablesbyaddingastatic
classwithconstants,propertiesandpublic
fields.Youcanalsodefinemethodswith
parameterstoaccessthestaticvariables.We
lookedanexampleofusingtheseglobal
variabletypes.
Finally:
Wediscussedissuesrelatingtoglobalvariablesandthreading.We
emphasizedtheusageofaccessroutines.

http://www.dotnetperls.com/globalvariable

3/3

You might also like