C# Variables and Naming Conventions

Like any other languages, CSharp has its own rules to declare variables. Variables are naming containers used to storing data value and then refer to the data simply by naming the container. Before you use a variable in a CSharp program, you must declare it.

Basic naming rules

  • Variable should start either with letter or underscore(_) or with symbol(@).
  • Variable's subsequent charaters can be any letter, underscore or number.
  • Variable's name should not be any reserved keyword.
  • CSharp variable names are case sensitive. For example, Customer and customer are two different variables.

CSharp Reserved Keywords

abstractaddasascending
asyncawaitbasebool
breakbybytecase
catchcharcheckedclass
constcontinuedecimaldefault
delegatedescendingdodouble
dynamicelseenumequals
explicitexternfalsefinally
fixedfloatforforeach
fromgetglobalgoto
groupifimplicitin
intinterfaceinternalinto
isjoinletlock
longnamespacenewnull
objectonoperatororderby
outoverrideparamspartial
privateprotectedpublicreadonly
refremovereturnsbyte
sealedselectsetshort
sizeofstackallocstaticstring
structswitchthisthrow
truetrytypeofuint
ulonguncheckedunsafeushort
usingvaluevarvirtual
voidvolatilewherewhile
yield

Example

string myVariable;  //valid variable name
int VAR12;			//valid variable name
double _Var;		//valid variable name
int 12Var;			//invalid variable name
int for;				//invalid variable name
string using;		//invalid variable name

/*  Case-sensitive Variables treated as seprate variables 
below variable are different  */
int MYVARIABLE;
int MyVariable;
int myVariable;

CSharp Variable Scope

The scope of a variable is the region of source code in which it is defined. In CSharp a global variable has global scope; it is defined outside method in CSharp code. On the other hand, variables declared within a method are defined only within the body of the method. They are local variables and have local scope.

In CSharp a local variable to be declared within any block, a block beginning with opening brace and ends with a closing curly brace. As a general rule, a local variable declared inside a scope are not visible outside the scope.

Within the body of a method, a local variable takes precedence over a global variable if decleaded with same name. If variables are declared as local or method parameter with the same name as a global variable, effectively hide the global variables:

Example

using System;
class VariableScopeDemo
{
		//Demonstrate lifetime of a variable
		static string str_global = "from global scope"; //global access scope
        static void Main(string[] args)
        {
			//Demonstrate block scope
            string str = "from local scope"; //local access scope
            printVal1(str);
            printVal1(str_global);  //str_global is accessible
            printVal2();
            Console.WriteLine(str_global);  //str_global can be accessed here
        }
        public static void printVal1(string str)
        {
            Console.WriteLine(str);
        }
        public static void printVal2()
        {
            Console.WriteLine(str_global);  //str_global is accessible
            Console.WriteLine(str);  		//str can not be accessed here
        }
}

CSharp Variable Conversion and Casting

There are situations when we require to assign one variable value to other variable. In CSharp, all type are not compitable hence all type conversions are not implicitly possible for example int variable can be assigned to float variable because they are compatible and int variable can implicitly be converted to float variable but wice versa is not possible because destination type range should be greater than source type range.

But if required, non compitable types can also be converted using a cast, since cast perform explicit type conversion.

Types of conversion in CSharp

  • Implicit type conversion - When two types are compitable and destination type range is greater than source type range.
  • Explicit type conversion - When two types are not compitable, it uses cast to perform explicit type conversion.
FromCan be convered To
sbyteshort,int,long,float,double,decimal
byteshort,ushort,int,uint,long,ulong,float,double,decimal
shortint,long,float,double,decimal
ushortint,uint,long,ulong,float,double,decimal
intlong,float,double,decimal
uintlong,ulong,float,double,decimal
longfloat,double,decimal
charushort,int,uint,long,ulong,float,double,decimal
floatdouble
ulongfloat,double,decimal

Example1

using System;
class ImplicitTypeConverionDemo
{
        static void Main(string[] args)
        {
			//Demonstrate implicitly conversion
            int _int = 10;
			float _float;
			_float = _int; //implicitly convert fron int to float
			
			long _long = 1233230;
			double _double;
			_double = _double * _long; //implicitly convert fron long to double
        }
        
}

Example2

using System;
class ExplicitTypeConverionDemo
{
        static void Main(string[] args)
        {
			//Demonstrate explicit conversion
            int counter = 10;
			string str = "Display total ";
			str = str + Convert.ToString(counter);
			
			int _int;
			float _float = 210.32;
			_int = (int)_float;
			//  or
			_int = Convert.ToInt32(_float);
			
			byte _byte;
			short _short = 8;
			_byte = (byte)_short;
			//  or
			_byte = Convert.ToByte(_short);
        }
        
}


 
SHARE THIS IF YOU LIKE!
submit to reddit

SUBSCRIBE FOR LATEST UPDATES
HAVE WE CONNECTED ON FACEBOOK?
TOP TUTORIALSTOP CODE EXAMPLESTOP LIVE DEMOLINKSSTAY CONNECTED
HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
PHP Tutorial
Developer Tools
Javascript
AngularJS
Google MAP API V3
ASP.NET
Javascript
AngularJS
Google MAP API V3
Contact Us
Advertise with Us
Privacy Policy
Disclaimer
Stay connected. We actually like you. If you want to get up to the minute updates, then connect with us on your fav below.
 
Twitter   Linkedin   Facebook   Google+    RSS   Pinterest
 
Protected by Copyscape Original Content Checker
 
 
Copyright ©2017 www.techstrikers.com Unauthorized reproduction/replication of any part of this site is prohibited.