C# Examples

C# Example Code


C# Variables and Naming Conventions

Like any other languages, C# 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.

C# Reserved Keywords

abstractaddasascendingasyncawaitbasebool
breakbybytecasecatchcharcheckedclass
constcontinuedecimaldefaultdelegatedescendingdodouble
dynamicelseenumequalsexplicitexternfalsefinally
fixedfloatforforeachfromgetglobalgoto
groupifimplicitinintinterfaceinternalinto
isjoinletlocklongnamespacenewnull
objectonoperatororderbyoutoverrideparamspartial
privateprotectedpublicreadonlyrefremovereturnsbyte
sealedselectsetshortsizeofstackallocstaticstring
structswitchthisthrowtruetrytypeofuint
ulonguncheckedunsafeushortusingvaluevarvirtual
voidvolatilewherewhileyield   

C# Variable Declaretion 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;

C# Variable Scope

The scope of a variable is the region of source code in which it is defined. In C# a global variable has global scope; it is defined outside method in C# 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 C# 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:

C# Variable Scope 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
        }
}

C# Variable Conversion and Type Casting

There are situations when we require to assign one variable value to other variable. In C#, 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 C#

  • 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

C# Implicitly Type Conversion Example

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
        }
        
}

C# Explicit Type Conversion Example

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);
	}
}