Download as pdf or txt
Download as pdf or txt
You are on page 1of 348

C# Tutorials | Process Myanmar Group

C# Programming Language Object Oriented L Modernize


Real world
Microsoft
Ecma ISO Programming language
C# A H .NetFrameWork
C#

C# Common Language Infrastructure (CLI)


CLI (High-level language) L Programming Languages
Operating System ( ) Platforms Architectres Execute
Runtime Environment Executable code
Infrastructure

C# Java Visual Basic C++ Power


C# Programming Language
C#
C# -

Modern, general purpose programming language


Object oriented
Component oriented
Easy to learn
Structured language
It produces efficient programs
It can be compiled on a variety of computer platforms
Part of .Net Framework

P C# Professional
language

1|Page C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Strong Programming Features Of C#


C# Libarary Feature
Application

Version
C# C#
Programming Language
Feature -

Boolean Conditions
Automatic Garbage Collection
Standard Library
Assembly Versioning
Properties and Events
Delegates and Events Management
Easy to use Generics
Indexers
Conditions Compilation
Simple Multithreading
LINQ and Lambda Expressions
Integration with Windows

2|Page C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# program
C# .Netframework .Net Application C#
program Running .Netframework C#
.Netframework

The .Net Framework

.Net framework

C#
C++
Visual Basic
Jscript
J# Programming Language Support )
.Netframework Revolutionay Platform
.Netframework Programming Language
C#
code Program VB code
.Netframework

.Net framework Application Project


Windows application
Web application
Web services

.Net framework - C# ,C++, Visual Basic ,Jscript,


COBOL Language Program
.Net framework ( ) .Netframework

3|Page C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Language C# Project
Library of Codes
-

Common Language Runtime (CLR)


The .Net Framework Class Libarary
Common Language Specification
Common Type System
Metadata and Assemblies
Windows Forms
ASP .Net and ASP .Net AJAX
ADO.Net
Windows Workflow Foundation (WF)
Windows Presentation Foundation (WPF)
Windows Communication Foundation(WCF)
Language Integrated Query (LINQ)

Integrated Development Environment (IDE) For C#

(Integrated Development Environment) IDE Software C#


program Microsoft IDE version (vs 2008,vs 2010
) New version
Download http://www.visualstudio.com download

Visual Studio 2010 (VS)

Visual C# 2010 Express (VCE)

Visual Web Developer

Visual Studio 2012 (vs)

downloadLink Compiler

4|Page C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Writing C# Programs on Linux or Mac OS

.Net Framework Windows operation System(OS) version


(.NetFramework 3.5,4,4.5 ) C# complier .Net Framework
C# program
Linux operation System Mac Os C
Mono .Net Framework open source Mono .Net
Framework windows Os operation system
( -Android, BSD, iOS, Linux, OS X, Windows, Solaris and UNIX
)

5|Page C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# program Program structure ( )


Program
Structure
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements & Expressions
Comments

Installing Visual Studio Professional 2012


Visual Studio 2012
Install Install

() Visual Studion Install Visual Studion DvD ( )


folder S . x Click
I Agree to the License terms and condition check box
check N x click

6|Page C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

) S A I B S A )
F I
F S F S )
Select A

7|Page C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

8|Page C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

) I S B
S A

) S S C
I

9|Page C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

) V S C S C
LA NCH Visual Studion program

10 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# Hello World Example


Program structure Programming Language
H P C# Program

) Visual studio 2012

) Create P

11 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

() New Project Project D B x


() .Net Framework version 3.5

() Visual C# windows

() Console Application

() Project Name HellowWorldApplication Ok Button

Code Writing and Exectue Project

12 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

() namespaces
( ) namespaces

() code ( ) statements Program entry


point ( )

() Program execute shortcut key 5 Error output


window

using System;

namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/*my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}

13 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Hellow World Program execute Shortcuts Key F5


Programmer Shortcuts Key
Execute Output
Hello World )
Command Prompt window H

using system: Program System namespace D


) Declear using keyword
namespace ( -
Using system; ) Declear namespace class method
Program

namespace HelloworldAppliction: HelloWorldApplication namespace HelloWorld class


namespace

class HelloWorld: HelloWorld class D Class


class member class method class constructor destructor
Constructor class

static void Main(string[] args): static void Main methodMain C# program entry
point (program ) Class methodMain
execute method

/*.*/ compile ignore


( ) program code ( ) statements

14 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

programer
program comment single commet mulitple
comment commet multiple commet single
comment //

Co . L H ) : System namespace Console Class


Console Class WriteLine method
WriteLine method H

Conosle.ReadKey() : Program console window


console.ReadKey() method ReadKey() method Keyboard key
key Ex

C# C S
Statements Ex ;
program Main method
File name Class name (Java )

Compile & Excute A C# Program

Visual Studio C# Progarm ( Hellow World Program) Compile ,


Execute project
create ( )

Visual Studio
Menu bar File New Project

Template window Visual C#
Console Application
Project Name Ok button Click
Solution Explorer P
code E

15 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Project run( )compile Menubar Run button ( ) f5


Hello World C P

Visual Studio IDE Program File


Compile
Compile

Text Editor
Text Editor C# code
file . ) Save
Command Prompt (Win+R)
.cs file save Directory (cd directory command
)
csc filename.cs (eg. csc Helloworld.cs ) E
.cs file Error filename.exe (eg. Helloworld.exe) generate

filename.exe (eg. Helloworld.exe) command prompt
Exectute E )
Command prompt Output (eg. Hello World )

16 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# object oriented programming language (OOP)


OOP program program object
Action object Object Action
( method) Object
Object Class
Object
object
object length( ) width( )
Attributes
Class Class
area object
M
OOP

Class

width
width
length

length

Object1 Object2

17 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# basic syntax Rectangle Class program


using System;
namespace RectangleApplication
{
class Rectangle
{
double length; // member variables
double width; // member variables
public void Acceptdetails()
{
length = 4.5;
width = 3.5;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}

class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();(r object )
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}

program execute Result

18 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Identifiers

C# Class name variable name function name user


Variable Name Identifier Name

Name Letter
Letter ( ) Digit (0-9) ( ) Underscore
D 0- ) name
Name Underscore ( _ ) Symbol (? - +!
@ # % ^ & * ( ) [ ] { })
C# Keyword (eg.as, Base,bool,break,byte ,etc) Name

C# Keywords
Keywords C# Language name
Keywords Reserved Keywords Contextual Keywords Reserved Keywords
C# language name Reserved Keywords
Identifier ( - string, as) Contextual Keywords
Identifier ( - int add) C# Keywords

Reserved Keywords

abstract As Base bool break byte case

Catch Char Checked class const continue decimal

default delegate do double else enum event

explicit extern false finally fixed float for

foreach Goto if implicit in In int


(generic
modifier
)
interfac internal is lock long namespac new
e e
Null object operato out out(generi override Params
r c
modifier)
private protecte public readonly ref return Sbyte
d
sealed short sizeof stackalloc static string Struct

19 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

switch This throw true try typeof Uint

ulong unchecke unsafe ushort using virtual void


d
volatile While

Contextual Keywords

Add Alias ascendi descending dynamic from Get


ng
global group into join let orderby Partial(type
)
Partial remove select set
(method)

20 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Variables
Program Mg Mg
12 Program
Variables Variable
Variable Variable Declear(
) D C M
variable D Syntax

datatype indentifier;
Datatype Data Type
string type int type
C# Data Type
Indentifier Indentifier
Chapter 4
variable string datatype

string student_name;
student_name variable
variable Mg Mg
variable student_name value ( )
string value value

student_name = Mg Mg;
variable declear
int datatype value

Int student_age = 12;

21 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Data Type User I D


) Computer Memory
(space )
( ) Data Type Input
D
Data Type Declearing ( )
Data Type C# Data Type
-
Value Types
Reference Types
Pointer Type

Value Types

Value Type Computer Memory stack


Declear Data Type
int,char,float Data Type number
alphabet floating point number Data Type
system value
visual studio 2010 version value Type

Type Represent Range Default


( ) Value
( )
Bool Boolen value True or Fale Flase

Byte 8-bit unsigned integer 0 to 255 0

Char 16-bit unicode character U +0000 to U +ffff \0


28 28
decimal 128-bit precise decimal (-7.9 x 10 to 7.9 x 10 ) x 0.0 M
0 to 28
values with 28-29 signficant 10
digits
-324
double 64-bit double-precision (+/-)5.0 x 10 to (+/-)1.7 0.0D
308
floating point type x 10
38 38
Float 32-bit single-precision -3.4 x 10 to 3.4 x 10 0.0F
floating point type
Int 32-bit signed interger type -2,147,483,648 to 0
2,147,483,647
Long 64-bit signed integer type -923,372,036,854,775,808 to 0L
923,372,036,854,775,807
sbyte 8-bit signed integer type -128 to 127 0

22 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Short 16-bit signed integer type -32,768 to 32,767 0

Uint 32-bit unsigned integer type 0 to 4,294,967,295 0

ulong 64-bit unsigned integer type 0 to 0


18,446,744,073,709,551,615
ushort 16-bit unsigned integer type 0 to 6,535 0

Data Type size sizeof method


program Data Type size sizeof method

using System;

namespace DataTypeApplication
{
class Program
{
static void Main(string[] args)
{
/*my first program in C# */
Console.WriteLine("Size Of Int Data Type: {\0}",sizeof(int));
Console.ReadKey();
}
}

program command prompt


Output

Size Of Int Data Type : 4

Reference Types

Reference Types computer Memory heap Reference


Types variable Data Data memory address
address Reference Types user-defined type
(Class,Interfaces,Delegates and Arrays) Predefined type (object Type and String type)
Value Type Reference Type

23 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Value Type Reference Type

int i=1; string s = Hello;


int j=2; string s1= s;

i 1 s
Hello
J 2 s1

Value type M int i


int j value type i j 1,2
string s Reference Type
string s Hello Hello
Memory address
Reference Type

using System;

namespace RefeenceType

{
struct Struct1
{
public int Value;
}
class Class1
{
public int Value = 0;
}
class Test
{
static void Main(string[] args)
{
Struct1 v1 = new Struct1();
Struct1 v2 = v1;
v2.Value = 123;

Class1 r1 = new Class1();


Class1 r2 = r1;
r2.Value = 123;
Console.WriteLine("Values: {0}, {1}", v1.Value, v2.Value);
Console.WriteLine("Refs: {0}, {1}", r1.Value, r2.Value);

24 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.ReadLine();
}
}
}

program command prompt


Output

Values: 0, 123

Refs: 123 ,123

Object Types

Object (System.Object) Data Type Base Class


Data Type Object Type
Value Type Data Type ( - Reference Type, Predefined Type
User-defined Type) Object Type
Boxing Unboxing Boxing Value
Type Object Type Unboxing Boxing Object
Type Value Type

Object Obj;
Obj = 100; // boxing

int I;

I = (int)Obj;//Unboxing

Dynamic Types
Dynamic Type Object Type Object Type Data Type
Dynamic Type Obect Type RunTime
(program ) variable Type
Dynamic Type

25 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

dynamic <variable_name> = value;


dynamic d = 20;

String Types

String value String Data Type (System.String) String


Type Object Type String value quoted )
@

string str="Tutrial Point";


string str=@"Tutrial Point";

Pointer Types

Pointer Type variable Data Type memory adress


C# Pointer Type C C++ Pointer Type
C# Pointer C unsafe Code
Chapter 39

Type* <Identifier>;
char* cptr;
int* iptr;

26 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Type Conversion Data Type Data Type


Type Conversion ()Implicit Type Conversion ()
Ex C smaller intergral type larger intergral type Child
Class Parent Class Implicit Type Convertion Explicit Type
Convertion C# pre-defined Functions ( .Converter.ToString() )
Explicit Type Convertion
cast operator

using System;

namespace TypeConvertion
{

Class convertion
{

static void Main(string[] args)


{
double d=567.74;
int i;
i= (int)d; //Explicit convertion
d= i; //Implicit convertion
Console.WriteLine(i);
Console.ReadLine();

}
}
}

27 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# Type Conversion Methods

S.N Methods & Description


ToBoolean
1
Data Type Boolean value
ToByte
2
Data Type Byte
ToChar
3 Data Type a single Unicode character

ToDateTime
4
integer ( ) string type date-time
ToDecimal
5
floating point ( ) integer type decimal
ToDouble
6
Data Type double type
ToInt16
7
Data Type 16-bit integer
ToInt32
8
Data Type 32-bit integer
ToInt64
9
Data Type 64-bit integer
ToSbyte
10
Data Type signed byte type
ToSingle
11 Data Type small floating point number

ToString
12
Data Type string
ToType
13
Data Type Data Type
ToUInt16
14 Converts a type to an unsigned int type.
Data Type unsigned int type
ToUInt32
15
Data Type unsigned long type
ToUInt64
16 Data Type unsigned big integer

28 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Variables Memory Data name


Program variable Variable
Data Type M Size Layout
Data Type Range M Data

C# Data type chapter 5 Data Type
(Cetegorized)
Type Example
Intergral types sbyte,byte,short,ushort,int,long,ulong and char
Floating point types float and double
Decimal types Decimal
Bolean type true or false values as assigned
Nullable types Nullable data types
Data Type C# Type
Data Type Data Type
enum reference type class
C# chapter

Variable Decleartion in C#

Variable ( )

<data_type> <variable_list>

variable <data_type>

C# data type ( char, int, float, double ( ) any user defined dat
type ) <variable_list> id identifier

29 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

identifier commas(,)

int i, j, k;
char c, ch;
float f, salary;
double d;

Variable
initialize ( )

int i = 100;

Variable Initialization in C#
equal sign (=)
ini general
variable_name = value;

Variable
equal (=)

<data_type> <variable_name> = value;

Variable initialization

int d = 3, f = 5; /* initializing d and f. */


byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */

program Variable

namespace VariableDeclaration

30 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
class Program
{
static void Main(string[] args)
{
short a;
int b;
double c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}

a = 10, b = 20, c = 30

Accepting Values From User

User Input Data ( user data) ReadLine()


function L ) Data =
variable variable Input Data
store( ) ReadLine() function System namespace console class

int num;
num = Convert.ToInt32(Console.ReadLine());

Convert.ToInt32() funtion user input data string int data type


Console.ReadLine() function user input data string data type
int num string int type Type

Lvalues And Rvalues in C#


C# Values Lvalues Rvalues

int g = 20;

31 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

statement C#
variable g L 20 equal ( = )
L g 20 g 20
Lvalues ( = )
Rvalues (=)
Statement Rvalue
statement compile-time error

10 = 20;

32 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Program fixed values ( ) constants


constants illterals constants basic
data type ( interger constant, floating constant, character constant or
string literal) Enumeration constant

Integer Literals
Decimal , Octal hexadecimal constant Hexadecimal
0x ( ) 0X ( 0xFeel) Octal 0
( 0123) Unsigned long Data Type Integer Literal
Unsigned U( )u Long
L( )l ( 30U,30L)
uppercase lowercase I

212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */

Integer Litreal Data type

85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

33 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Floating-Point Literals
Floating-Point Literal integer, Decimal point (fractional)
(exponent) Floating Point literal Decimal Form ( )
(exponent Form) F -P L

3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */

Floating-Point Literal decimal form


Decimal point exponent (
3.14159) Ex F integer part fractional part
( ) ( 31345E-5L) exponent
e( )E

Character Constants
Character Literal single quotes ) ( x )
character type variable Charater Literal
Character escape sequence \ ( )
universal character \ 02 0)
escape sequence code
Escape Sequence Meaning
\\ \ character
\ character
\ character

\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\000 Octal number of one to three digits

34 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

\xhh Hexadecimal number of one or more digits

program escape sequence character


program

using System;

namespace characterconstant
{
class character
{
static void Main(string[] args)
{
Console.WriteLine("Hello\tWorld\n\n");
Console.ReadLine();
}
}
}

Hello World

String Literals
String Literals double quotes ( ) ( @ )
String literal Character literal String Character
Multipel Lines String Literal S S
()
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
@"hello dear"

Defining Constant
Varaiable (Constant) const
Keyword Constant Varaiable statement
Constant
const <data_type> <constant_name> = value;

35 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Constant Varaiable

using System;

namespace constant
{
class constantvairable
{
static void Main(string[] args)
{
const double pi = 3.14159; // constant declaration
double r;
Console.WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());
double areaCircle = pi * r * r;
Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console.ReadLine();
}
}
}

Enter Radius:
3
Radius: 3, Area: 28.27431

36 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Operators program
( ) statement symbol
( ) variable a 5 2
int a = 5 * 2 ; statement 5 2
(*) operator 10
variable a (=) operator
Computer ( ) Program
C# built-in operator ()

Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators

Arithemetic Operators

Operatort Arithemetic Operator C#
Arithmetic operator A (value)
B
result

Operator Description Example


+ A + B 30

- A B -10

* A * B 200

/ B / A 2

37 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

% A % B 0


++ A++ 11


-- A-- 9

Arithmetic operator

using System;

namespace OperatorsAppl {
class Program {
static void Main(string[] args)
{
int a = 21;
int b = 10;
int c;
c = a + b;
Console.WriteLine("Line 1 - Value of c is {0}", c);
c = a - b;
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a * b;
Console.WriteLine("Line 3 - Value of c is {0}", c);
c = a / b;
Console.WriteLine("Line 4 - Value of c is {0}", c);
c = a % b;
Console.WriteLine("Line 5 - Value of c is {0}", c);
c = a++;
Console.WriteLine("Line 6 - Value of c is {0}", c);
c = a--;
Console.WriteLine("Line 7 - Value of c is {0}", c);
Console.ReadLine();
}
}
}

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2

38 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

Relational Operators

Operators Relational Operators A 10 B 20
A==B A B (not true)
false ( )
C# relational operator

Operator Description Example


/
(A == B)
== condition
(false)

/ (A != B)
!=
condition (true)
(A > B)
>
(false)
(A < B)
<
(true)
( )
(A >= B)
>=
(false)
( )
( )
(A <= B)
<=
(true)
( )

using System;

class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;

if (a == b)
{
Console.WriteLine("Line 1 - a is equal to b");

39 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
else
{
Console.WriteLine("Line 1 - a is not equal to b");
}
if (a < b)
{
Console.WriteLine("Line 2 - a is less than b");
}
else
{
Console.WriteLine("Line 2 - a is not less than b");
}
if (a > b)
{
Console.WriteLine("Line 3 - a is greater than b");
}
else
{
Console.WriteLine("Line 3 - a is not greater than b");
} /* Lets change value of a and b */

a = 5;
b = 20;

if (a <= b)
{
Console.WriteLine("Line 4 - a is either less than or equal to b");
}
if (b >= a)
{
Console.WriteLine("Line 5-b is either greater than or equal to b");
}
}
}

Line 1 - a is not equal to b


Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

Logical Operators
C# Logical oprator A
B True False True B False

Operator Description Example
(A && B)
&&
condition (false)

40 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

true ( )
condition
( )
( )
(A || B)
|| condition true
(true)
condition

( ) ture ( ) !(A && B)
!
(true)

Program Logical operator


using System;

namespace LogicalOperators
{
class Program
{
static void Main(string[] args)
{
bool a = true;
bool b = true;

if (a && b)
{
Console.WriteLine("Line 1 - Condition is true");
}
if (a || b)
{
Console.WriteLine("Line 2 - Condition is true");
} /* lets change the value of a and b */

a = false;
b = true;

if (a && b)
{
Console.WriteLine("Line 3 - Condition is true");
}
else
{
Console.WriteLine("Line 3 - Condition is not true");
}
if (!(a && b))
{
Console.WriteLine("Line 4 - Condition is true");
}
Console.ReadLine();
}
}

41 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Line 1 - Condition is true


Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

Bitwise Operators
Bitwise Operators bits
O C# Bitwise Operator

P Q P & Q (AND) P | Q (OR) P ^ Q (XOR)
0 0 0 0 0
0 1 0 1 1
1 0 0 1 0
1 1 1 1 1
Variable A 60 Variable B 13 Bitwise
Operator
A = 60;

B = 13;

/* A B binary format */

A = 0011 1100

B = 0000 1101

/*---------------*/

A & B = 0000 1100

A | B = 0011 1101

A ^ B = 0011 0001

~A = 1100 0011

Bitwise Operator
A B 63 13
Operator Description Example

42 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Binary AND Operator binary 0 0


0 0 1 ( ) 1 0 0 (A & B) 12
&
1 1 1 (0000 1100)
1 1
Binary AND Operator binary ( )
(A | B) 61
| 1 1
(0011 1101)
0 0
Binary XOR Operator binary
(A ^ B) 49
^ 1 1 0( )
(0011 0001)
1 0
(~A ) -60
~ Binary
(1100 0011)
Binary Left Shift Operator Binary value
A << 2 240
<<
(1111 0000)

Binary Right Shift Operator . Binary value
A >> 2 15
>>
(0000 1111 )

Bitwise Operator Program


using System;

namespace Bitwise_Operators
{
class Program
{
static void Main(string[] args)
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b;

/* 12 = 0000 1100 */
Console.WriteLine("Line 1 - Value of c is {0}", c);
c = a | b; /* 61 = 0011 1101 */
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a ^ b; /* 49 = 0011 0001 */
Console.WriteLine("Line 3 - Value of c is {0}", c);
c = ~a; /*-61 = 1100 0011 */
Console.WriteLine("Line 4 - Value of c is {0}", c);
c = a << 2; /* 240 = 1111 0000 */
Console.WriteLine("Line 5 - Value of c is {0}", c);
c = a >> 2; /* 15 = 0000 1111 */

43 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("Line 6 - Value of c is {0}", c);


Console.ReadLine();
}
}
}

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Assignment Operators
Variable value (assign) Assignment Operators
variable int i value (10) i=10
Assignment Operator =
C# Assignment Operator

Operator Description Example
S C = A + B
= (value) A B C
(assign)
Add and Assignment operator
C += A
(value)
+= A C C


Subtract and Aassignment operator
C -= A C
(value)
-= A
C

Multiply and Assignment operator
C *= A
(value)
*= C=C * A


Divide AND assignment operator
C /= A
(value)
/= C = C / A

44 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Modulus AND assignment operator


C %= A
(value)
%= C = C % A


C <<= 2 C = C
<<= Left shift A
<< 2
C >>= 2 C = C
>>= Right shift and A
>> 2
C &= 2 C = C &
&= Bitwise and A
2
C ^= 2 C = C ^
^= bitwise exclusive OR and A
2
C |= 2 C = C |
|= bitwise inclusive OR and A
2
program Assignment Operator

using System;

namespace Assignment_Operators
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int c;
c = a;
Console.WriteLine("Line 1 - = Value of c = {0}", c);
c += a;
Console.WriteLine("Line 2 - += Value of c = {0}", c);
c -= a;
Console.WriteLine("Line 3 - -= Value of c = {0}", c);
c *= a;
Console.WriteLine("Line 4 - *= Value of c = {0}", c);
c /= a;
Console.WriteLine("Line 5 - /= Value of c = {0}", c);
c = 200;
c %= a;
Console.WriteLine("Line 6 - %= Value of c = {0}", c);
c <<= 2;
Console.WriteLine("Line 7 - <<= Value of c = {0}", c);
c >>= 2;
Console.WriteLine("Line 8 - >>= Value of c = {0}", c);
c &= 2;
Console.WriteLine("Line 9 - &= Value of c = {0}", c);
c ^= 2;
Console.WriteLine("Line 10 - ^= Value of c = {0}", c);
c |= 2;

45 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("Line 11 - |= Value of c = {0}", c);


Console.ReadLine();
}
}
}

Line 1 - = Value of c = 21
Line 2 - += Value of c = 42
Line 3 - -= Value of c = 21
Line 4 - *= Value of c = 441
Line 5 - /= Value of c = 21
Line 6 - %= Value of c = 11
Line 7 - <<= Value of c = 44
Line 8 - >>= Value of c = 11
Line 9 - &= Value of c = 2
Line 10 - ^= Value of c = 0
Line 11 - |= Value of c = 2

Misc(Miscellaneous) Operators
typeof(), sizeof() , As Misc Operator

Operator Description Example
sizeof(int), will
sizeof() Data type size )
return 4.
Typeof
typeof() Class type )
(StreamReader);
&a; will give actual
& Variable address ) address of the
variable.
* Variable (point) *a; will pointer to a variable.
If Condition is true ?
?: Conditional Expression Then value X :
Otherwise value Y
If( Ford is Car) //
is Object type checks if Ford is an
object of the Car class.
Object obj = new
Object class StringReader("Hello");
As
StringReader r = obj
as StringReader;

46 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;

namespace Misc_Operators {
class Program
{
static void Main(string[] args)
{
/* example of sizeof operator */
Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of short is {0}", sizeof(short));
Console.WriteLine("The size of double is {0}", sizeof(double));

/* example of ternary operator */


int a, b;
a = 10;
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
b = (a == 10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
Console.ReadLine();
}
}
}

The size of int is 4


The size of short is 2
The size of double is 8
Value of b is 30
Value of b is 20

Operators Precedences in C#
Statement Operator
Operator Operator
Operator
( precedence ) int x = 7 + 3 * 2;
statement x 20
13 Operator (*) precedence Operator +
precedence Operator (*) 3 2
6 7 13 assignment Operator
(=) (=)

Operator * Operator + Operator =
13 x x 13

47 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Operator precedence ( )

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

using System;

namespace Operators_Precedence
{
class Program
{
static void Main(string[] args)
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
Console.WriteLine("Value of (a + b) * c / d is : {0}", e);
e = ((a + b) * c) / d; // (30 * 15 ) / 5
Console.WriteLine("Value of ((a + b) * c) / d is : {0}", e);
e = (a + b) * (c / d); // (30) * (15/5)
Console.WriteLine("Value of (a + b) * (c / d) is : {0}", e);

48 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

e = a + (b * c) / d; // 20 + (150/5)
Console.WriteLine("Value of a + (b * c) / d is : {0}", e);
Console.ReadLine();
}
}
}

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

49 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Decision Making
Program
(Decision
Making) )
Statement (
)


/ Program

40
40 40
if ... else statement 40
( ) Pass
Fail Console.WriteLine(string str) method
int mm_marks;
mm_marks = Convert.ToInt32(Console.ReadLine());
if (mm_marks >= 40)
{
Console.WriteLine("Pass");
}
Else
{
Console.WriteLine("Fail");
}
Console.ReadKey();

D M

Programmer D M

50 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Decision Making Structure


Programming Language

Condition
if condition is
if condition is
false
true

Conditionl

code

C# Decision making Statement

Statement Description
if statement boolean ( ( ) (true/flase) )
Expression statement if statement
expression (true) statement (if
if statement { } )code
(false) if
statement if statement

51 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

if ... else statement if statement


if statement else statement
if statement expression
(false) else
if ... else statement
statement code statement
else statement
if / if ... else statement

if statement if ... else statement if
statement if ... else statement
nested if statement statement

nested if statement
Variable value list ( )

switch statement
switch statement
value List ( )


if statement switch statement
nested switch statement switch statement

If Statement
C# program statement (Line by Line )
Program statement
statement

Condition boolean (
( ) (true/flase) ) Expression if statement
if statement
(syntax)

If (boolean expression) // true (or) false


{
// { } statement ( ) statement
// bollean expression (true) statement

52 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

//
}
if statement / (boolean expression) { } code
( ) statement { } code ( )
statement if statement

if condition is true
Condition

if condition is false

If code

variable a integer type a 10


assign if statement a 20
a 20
Console.WriteLine(); "a is less than 20" output

53 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;
namespace ifStatement
{
class Program
{
static void Main(string[] args)
{
/* local variable */
int a = 10;

/* a 20 if statement */
if (a < 20)
{
/* a 20 (condition is true) 20 print
*/
Console.WriteLine("a is less than 20");
}
Console.WriteLine("value of a is : {0}", a);
Console.ReadLine();
}
}
}

a is less than 20
value of a is : 10

if...else Statement

if statement else option


if statement ... if ...
else statement syntax

If (boolean expression)
{
// { } statement ( ) statement
// bollean expression (true) statement
//
}
else
{
// bollean expression ) else { }
// statement (true)

54 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// if { } else
}

if ... else statement flow diagram


if condition is false if condition is true


Condition

Else code If code

if statement if ... else statement Program


using System;

55 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

namespace ifelseStatement
{
class Program
{
static void Main(string[] args)
{
/* local variable */
int a = 100;

/* a 20 if statement */
if (a < 20)
{
/* a 20 (condition is true) 20 print
*/
Console.WriteLine("a is less than 20");
}
else
{
/* a 20 (condition is false) 20
print */
Console.WriteLine("a is not less than 20");
}
Console.WriteLine("value of a is : {0}", a);
Console.ReadLine();
}
}
}

a is not less than 20;


value of a is : 100

The if...else if...else Statement


Else if ... else statement

if ... else if ... else statement
-
if statement else
else statement if
if statement else if
else
else else if statement

56 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

If (boolean expression1)
{
// expression1 { } statement
}
else if (boolean expression2)
{
// expression2 { } statement
}
else if (boolean expression3)
{
// expression3 { } statement
}
else
{
// expression1, expression2 expression3 { }
// statement
}

using System;

namespace ifelseifelse
{
class Program
{
static void Main(string[] args)
{
/* local variable */
int a = 100;
/* boolean condition */
if (a == 10)
{
/* if condition a 10 */
Console.WriteLine("Value of a is 10");
}
else if (a == 20)
{
/*else if condition a 20 */
Console.WriteLine("Value of a is 20");
}
else if (a == 30)
{
/*else if condition a 30 */
Console.WriteLine("Value of a is 30");
}
else
{
/* condition */
Console.WriteLine("None of the values is matching");

57 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
Console.WriteLine("Exact value of a is: {0}", a);
Console.ReadLine();
}
}
}

None of the values is matching


Exact value of a is: 100

Nested if Statement

if statement,if ... else statement if statement,if ... else statement


statement if
statement,if ... else statement
nested if statement Condition nested if
statement

if( boolean_expression 1)
{
// expression1 { } statement
if(boolean_expression 2)
{
// expression1 { } statement
//
}

using System;

namespace nestedifstatement
{
class Program
{
static void Main(string[] args)
{
/* */
int a = 100;
int b = 200;

/* condition / */

58 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

if (a == 100)
{
/* condition ( )a 100 */
if (b == 200)
{
/* condition ( )a 200 */
Console.WriteLine("Value of a is 100 and b is 200");
}
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200

switch Statement
Switch Statement Variable value value list
value
statement value case
Switch statement case Switch statement
variable switch case
case block statement case block
switch statement

switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */

59 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

statement(s);
}

switch statement
switch statement Expression integral ( ) enumerated type
Class type integral ( ) enumerated type
conversion function
switch stateement case statement number type
case statement case
value colon : ) Statement

constant expression case switch statement variable data type
Case constant ( )
switch variable case case block
statement break statement

break statement switch switch
statement
case break statement case block statement
Break statement Break statement switch
statement
switch statement ( ) case default case
default case break statement

60 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

expression

code block 1

code block 2

code block 3

using System;

namespace switchStatement
{
class Program
{
static void Main(string[] args)
{

/* local variable definition */

61 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

char grade = 'B';


switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default: Console.WriteLine("Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
}
}
}

Well done
Your grade is B

//nested switch
//the ?: operator

62 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Block ( ) statements loop


Loop ( )
statement
Statement
S

Hello world Program
-
Console.WriteLine(Hello world);
Hello world

Console.WriteLine(Hello world);

Console.WriteLine(Hello world);
Program
Code Statement Loop

for loop

Console.WriteLine(Hello world);
Statement loop

For(int i=0;i<10000;i++)
{
Console.WriteLine(Hello world);
}

63 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# Programming Language Control Structures


execute Execute
statement ( ) group statement loop statement
loop statement Programming
Language

Init

if condition

is false
Conditiona
l Code
if condition
is true

Code Block

Increment

64 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Looping C# looping

Loop Type Description


While loop while loop true statement
group statement
Condition
loop body
For loop For loop statement
sequence code


Dowhile loop While loop
D loop body
condition

Foreach loop Collection ( ) element
foreach
loop
foreach

string array element
foreach string

Nested loops Looping
looping

Nested loop

While Loop
Condition ( ) while
loop statement code body statement
while loop Condition loop
statement
C# while loop syntax

while(condition)
{

65 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

statement(s);
}

statement(s) single statement block statement


expression condition
Condition true ( ) loop
while loop ( )
loop loop statement
condition false ( ) loop

While (condition )
{
Codition Code ;
}

Condition

if condition is true

Code Block

if condition is false

Condition Code Block Condition


Condition Code Block Condition

66 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Condition True ( ) Loop


Condition Result False ( ) Loop Body
while loop while loop Condition
Code Block Statement

using System;

namespace loop
{
class Wileloop
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10; /* while loop execution */
while (a < 20)
{
Console.WriteLine("value of a: {0}", a);
a++;
}
Console.ReadLine();
}
}
}

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

For Loop
C# language for loop syntax

for ( init; condition; increment )


{
statement(s);
}
For loop

67 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

() For loop init step ( )


init variable loop control
variable Initilize ( )
init statement blank
Condition Semicolon ; )
() Loop body Statement
Condition Condition loop
Loop statement

() Loop body increment statement Increment
statement Loop control variable
increment statement blank
() Condition loop increment
step Condition
condition
Loop

68 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

for(init ; condition ; increment


{
Codition Code ;
}
Init

Condition

if condition if condition
is true is false

Code Block

Increment

using System;

69 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

namespace Loop
{
class ForLoop
{
static void Main(string[] args)
{
for (int a = 10; a < 20; a = a + 1)
{
Console.WriteLine("value of a: {0}", a);
}
Console.ReadLine();
}
}
}

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Do...While Loop
Do..while loop for loop while loop loop body
( Loop ) Condition while loop
Loop
C# D syntax

do
{
statement(s);
}
while( condition );
D looping conditional expression condition
Loop Statement(s) ( ) Code Block
Condition Condition Loop statement
while loop

70 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

do
{
Codition Code ;
}while (condition)

Code Block

if condition
is true

Condition

if condition
is false

using System;

namespace Loop
{
class dowhileloop
{
static void Main(string[] args)
{
int a = 10; /* do loop execution */
do
{

71 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("value of a: {0}", a);


a = a + 1;
} while (a < 20);
Console.ReadLine();
}
}
}

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Foreach Loop
Collection ( ) Elements ( ) Value
foreach loop foreach loop
L , , ) foreach loop Loop
initialization, termination increment/decrement characteristics
Collection element one by one

foreach (string str in arr)


{
}
str Data type arr string array str arr
value value
Loop Block arr value Loop
Loop arr value
arr string array
Data Type foreach array size
array value foreach
loop

using System;

namespace foreachLoop

72 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
class Program
{
static void Main(string[] args)
{
string[] strArr = { "a","b","c","d","e"};
foreach (string s in strArr)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
}
}

a
b
c
d
e

Nested Loops
C# loop ( ) loop
Nested Loop
Syntax Nested For loop

for ( init; condition; increment )


{
for ( init; condition; increment)
{
statement(s);
}
statement(s);
}

Nested While loop

while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

73 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Nested Do..while loop

do
{
statement(s);
do
{
statement(s);
}while( condition );

}while( condition );
Nested foreach loop

foreach(string str1 in arr1)


{
foreach(string str2 in arr2)
{
statement(s);
}
}
Nested loop Loop type
while loop for loop for loop
while loop program for loop 2
100 prime number

using System;

namespace nestedloops
{
class nestedLoops
{
static void Main(string[] args)
{
/* local variable definition */
int i, j;
for (i = 2; i < 100; i++)
{
for (j = 2; j <= (i / j); j++)
if ((i % j) == 0)
break; // if factor found, not prime
if (j > (i / j))
Console.WriteLine("{0} is prime", i);
}
Console.ReadLine();
}
}
}

74 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

Loop Controls Statements


Block statements
Loop Controls Statements loop
Break Statement continue Loop Contorls Statements
loop controls statements

Contorl Statement Description
Break statement Break statement loop( )
switch statement
control statement
Loop
Break statement
loop ( ) switch statement

Continue statement Continue statement loop
( ) switch statement (current) loop
Loop

75 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

statement

Break Statement
C# break statement
Loop loop
statement

Break statement switch statement
Nested loop (Loop loop
) break statement inner loop inner loop statement
C# break statement

Break;

Conditional

if condition is true

Conditio Break

if condition is false

76 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;

namespace mybreakofeg
{
class mybreak
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* while loop execution */
while (a < 20)
{
Console.WriteLine("value of a: {0}", a);
a++;
if (a > 15)
{
/* terminate the loop using break statement */
break;
}
}
Console.ReadLine();
}
}
}

program execute result

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

Continue Statement
Continue Statement break statement terminate loop
statement loop ( )
For loop continue statement condition
increment While D condition
program continue statement C#
continue statement

77 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

continue;

Conditional Code

Continue
if condition is true

Condition

if condition is false

using System;
namespace continueeg
{
class mycontinue
{
static void Main(string[] args)
{
/* local variable definition */

78 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

int a = 10;
/* do loop execution */
do
{
if (a == 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;
} while (a < 20);
Console.ReadLine();
}
}
}

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

The Inifinite Loop

Condition false ( ) loop infinite loop


loop Infinite loop
loop for loop
Infinite loop for loop expressions empty

using System;

namespace infiniteloop
{

79 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

class myinfinite
{
static void Main(string[] args)
{
for (; ; )
{
Console.WriteLine("Hey! I am Trapped");
}
}
}
}

program Conditional Expression empty condition


program
execute infinite loop
programmar inifinite loop program ( for(;;) )

80 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Hidden Data Data Function Property


E

Access Specifiers
Access Specier E
Access Specifier Member Variable ( ) Member Function
member variable
C# Access Specifier ()
Access Specifier
-

Declared accessibility Meaning

Public Access Specifier



Protected class
Class Base
Derived Class

Internal (same assembly) File(*.cs)


Protected internal Class Derived Class


(same assembly)
File

Private class

81 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Public Access Specifier


Class Member Variable ( ) Member Function Function
object Public Access Specifier
Public Access Specifier Public
Member class

using System;
using System.Collections.Generic;
using System.Text;

namespace encapsulation
{
class Rectangle
{
//member variables
public double length;
public double width;

public double GetArea()


{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle

class publicaccessspecifier
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();

}
}
}

82 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Length: 4.5
Width: 3.5
Area: 15.75
Member variable length width Public Member
function Main () Fucntion rectangle class object r

Member funtion GetArea() Display() Function instance object

Display () function Public Main() function
object r

Private Access Specifier


Class Member variable ( ) Member function Function object
Private access specifier hide Same class
function Private member variable Private member variable
object H
Class Object

using System;
using System.Collections.Generic;
using System.Text;

namespace privateaccesspecifier
{
class Rectangle { //member variables
private double length;
private double width;
public void Acceptdetails()
{
Console.WriteLine("Enter Length: ");
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
}
public double GetArea() {
return length * width;
}
public void Display()

83 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class privateaccess
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();

}
}
}

Enter Length:
4.4
Enter Width:
3.3
Length: 4.4
Width: 3.3
Area: 14.52
Member variable length width Private class
main function length width length
width Member Variabler length width
Acceptdetail () function GetArea() function Display () function Class
Acceptdetail () function GetArea() function
Display () function public object r
main () function

Protected Access Specifier

Protected Access Specifier Base Class Child Class base


class member variable member function I

84 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Internal Access Specifier

Internal Access Specifier member variable member function


(current) Assembly Function Object
Application Class Function

using System;
using System.Collections.Generic;
using System.Text;

namespace internalaccesspecifier
{
class Rectangle { //member variables
internal double length;
internal double width;

double GetArea() {
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class internalaccess
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length=4.5;
r.width=3.5;
r.Display();
Console.ReadLine();

}
}
}

Length: 4.5

Width: 3.5

Area: 15.75

85 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

GetArea() Function acces specifier Default


Protected Internal Access Specifier

Protected internal access specifier class member variable member


function Application I child class

86 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

(statement ) ( )
statements Method
Function
Method ( ) Function Program
Code code
Program
code Method ( ) Function
Program

C# program class class Main
Method Method Program
Method Method
Method -
Define the method ( Method )
Call the method ( Method )

Defining Methods in C#
Method -
(Name)
(Return Type)
( Accesss Specifier)
Element of its structure Defining Method
Syntax

87 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

<Access Specifier> <Return Type> <Method Name>(Parameter List)


{
Method Body
}

Access Specifier (Object,Function) Method



Return type Method Data Type
Method
( ) Return Type void
Method name Method
Method C#
Parameter list Method
Method Data
Data Method Parameters Passing
Data Method Parameters Passing

Method body Method { } ) statement

...
class NumbersManiPulator
{
public int FindMaxNumber(int num1, int num2)
{
/* local variables declaration */
int result;
if (num1 > num2)
result = num1;
else result = num2;
return result;
}
}

...

88 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Calling Methods in C#

D M ) Method
Calling Methods

using System;

namespace CallingMethods
{
class NumbersManiPulator
{
static int FindMaxNumber(int num1, int num2)
{
/* local variables declaration */
int result;
if (num1 > num2)
result = num1;
else result = num2;
return result;
}
static void Main(string[] args)
{
/* local variables definition */
int x = 2100;
int y = 500;
int ret;
//calling the FindMaxNumber method
ret = FindMaxNumber(x, y);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}

Max value is : 2100

Method Access Specifier Public Method


Class FindMaxNumber() Method Public
Class Class
Class Object Object
Method FindMaxNumber()
Method Class NumbersManiPulator C Testing Class

89 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

FindMaxNumber ) M Class NumbersManiPulator NMP


Object NMP Object FindMaxNumber Method

using System;

namespace CallingMethodFromOtherClass
{
class NumbersManiPulator
{
public int FindMaxNumber(int num1, int num2)
{
/* local variables declaration */
int result;
if (num1 > num2)
result = num1;
else result = num2;
return result;
}
}
class Testing
{
static void Main(string[] args)
{
/* local variables definition */
int x = 2100;
int y = 500;
int ret;
NumbersManiPulator MNP = new NumbersManiPulator();

//calling the FindMaxNumber method


ret = MNP.FindMaxNumber(x, y);
Console.WriteLine("Max value is : {0}", ret);
Console.ReadLine();
}
}
}

Max value is : 2100

Recursive Method Call


M C Call,Method Method
Method Body
M C ) Recurisive Method Call
Condition Method L Return value

90 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Loop First-In,Last-Out
Recursive Method Factorial

using System;

namespace RecursiveMethods
{
class NumbersManiPulator
{
public int Factorial(int num)
{
/* Local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = Factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args)
{
NumbersManiPulator NMP = new NumbersManiPulator();
//Calling the Factorial method
Console.WriteLine("Factorial of 4 is : {0}", NMP.Factorial(4));
Console.WriteLine("Factorial of 6 is : {0}", NMP.Factorial(6));
Console.WriteLine("Factorial of 8 is : {0}", NMP.Factorial(8));
Console.WriteLine("Factorial of 10 is : {0}", NMP.Factorial(10));
Console.ReadLine();
}
}
}

Factorial of 4 is : 24
Factorial of 6 is : 720
Factorial of 8 is : 40320
Factorial of 10 is : 3628800

91 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Passing Parameters to a Method


Method ) ( ) Parameters
( - M )) Paratemters
Method Paratemeters Paratemeters
Parameter Call Method Argument
( ) values Paratemeters Method
Paratemeters Paratemeters
(Arguments)
P P P P ()

Mechanism Description

Value parametValue parameters Arguments (actual value) Method Copy


Parameter

Method Value Parameters


( )
Argument

Reference parameters Value Parameter Arguments(actual value) Memory


Location Copy Argument Memory
Location
Arguments

Output parameters Reference Parameters Copy


Arguments(actual value) Memory Location (actual value)
output ( result)
out parameter parameter assign
Error

Params Array Arguments (actual value) Array Method


Copy Arguments

92 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Value Parameter

Passing Parameters Value Parameter Passing Default Mechanism


( ) Arguments (actual value) Method Copy
Parameter Value Parameters
( ) Argument

using System;

namespace ValueParameters
{
class NumberManiPulator
{

public void swap(int p, int q)


{
int temp; temp = p;
/* save the value of x */
p = q;
/* put y into x */
q = temp;
/* put temp into y */
}
static void Main(string[] args)
{
NumberManiPulator n = new NumberManiPulator();
/* Local variable definition */
int x = 1000;
int y = 500;
Console.WriteLine("Before swap, value of x : {0}", x);
Console.WriteLine("Before swap, value of y : {0}", y);
/* Calling a function to swap the values */
n.swap(x, y); Console.WriteLine("After swap, value of x : {0}", x);
Console.WriteLine("After swap, value of y : {0}", y);
Console.ReadKey();
}
}
}

Before swap, value of x :1000


Before swap, value of y :500
After swap, value of x :500
After swap, value of y :1000

93 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Reference Parameters
Referenc Parameters Aragument value Copy
Arguments Memory Location Copy Memory
value
Arguments
Reference Parameters

using System;

namespace ReferenceParameters
{
class NumberManiPulator
{
public void swap(ref int a, ref int b)
{
int temp;
temp = a;
/* save the value of a */
a = b;
/* put y into a */
b = temp;
/* put temp into b */
}
static void Main(string[] args)
{
NumberManiPulator n = new NumberManiPulator();
/* Local variables definition */
int x = 1000;
int y = 500;
Console.WriteLine("Before swap, value of x : {0}", x);
Console.WriteLine("Before swap, value of y : {0}", y);
/* Calling x function to swap the values */
n.swap(ref x, ref y);
Console.WriteLine("After swap, value of x : {0}", x);
Console.WriteLine("After swap, value of y : {0}", y);
Console.ReadLine();
}
}
}

Before swap, value of x :1000


Before swap, value of y :500
After swap, value of x :500

94 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

After swap, value of y :1000

Output Parameters
Method return statement value )
vlaue value
Output Parameters Reference
Parameters Copy Arguments(actual value) Memory
Location (actual value) output ( result)
out parameter parameter assign

using System;

namespace OutputParameters
{
class NumberManiPulator
{
public void getValue(out int x)
{
int temp = 88;
x = temp;
}
static void Main(string[] args)
{
NumberManiPulator n = new NumberManiPulator();
/* Local variable definition */
int a = 500;
Console.WriteLine("Before method call, value of a : {0}", a);
/* Calling a function to get the value */
n.getValue(out a);
Console.WriteLine("After method call, value of a : {0}", a);
Console.ReadLine();
}
}
}

Before method call, value of a :500


After method call, value of a : 88

95 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Params Array
Params Array Parameters Array Parameters Array
Arguments
Params Array M D Params
keyword M C Data Type
I Arguments

using System;

namespace ParamsArray
{
class NumberManiPulator
{
public int AddElements(params int[] arr)
{
int sum = 0;
foreach (int i in arr)
{
sum += i;
}
return sum;
}
static void Main(string[] args)
{
NumberManiPulator app = new NumberManiPulator();
int sum = app.AddElements(312, 104, 50, 5617, 189);
Console.WriteLine("The sum is: {0}", sum);
Console.ReadKey();
}
}
}

The sum is:6272

96 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# nullables type special data type Data Type


Nullable Type Null value Nullables Type
-2,147,483,648 2,147,483,647 Boolean Type
Integer Type Data Type Null value special data type
okboolen boolen type variable
okboolen true false okboolen
nullable type Declear ?
bool? okboolen ; nullable type true,false

null okbollen = null; null


Syntex
Nullables type

< data_type> ? <variable_name> = null;

Nullables data type x

using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main(string[] args)
{
int? num1 = null;
int? num2 = 45;
double? num3 = new double?();
double? num4 = 3.14157;

bool? boolval = new bool?();

// display the values


Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}",
num1, num2, num3, num4);
Console.WriteLine("A Nullable boolean value: {0}", boolval);

97 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.ReadLine();
}

}
}

Nullables at Show: , 45, , 3.14157


A Nullable boolean value:
Null coalescing operator ?? Null coalescing operator nullable
vaule types reference types Data Type Nullable data type
First operand second
operand value First operand null first operand
value x

using System;
namespace CalculatorApplication
{
class NullablesAtShow
{

static void Main(string[] args)


{

double? num1 = null;


double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34;
Console.WriteLine(" Value of num3: {0}", num3);
num3 = num2 ?? 5.34;
Console.WriteLine(" Value of num3: {0}", num3);
Console.ReadLine();

}
}
}

Value of num3: 5.34


Value of num3: 3.14157

98 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Data Type Eelement Arrays


Element
Element
Array Index
Index 0
values element Array data
variable
variable
0, 1. array
[0], [1]. [ ] variable array
Array element array index
Array
element

First Element Last Element

Number[0] Number[1] Number[2] Number[3] Number[4]

Number[0] Array Array First Element


Index 0 Array

Declearing Array

C# Array

99 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Datatype[] arrayName;

Datatype array data


integer ( ) array int

[] array size ( )
array 10 [10]

arrayName array

double [] myarray;

Initializaing an Array
array Declear
array array
initializating array (size)
(initialize ) array value (assign)

Array reference type array
Initilize new keyword

double [] myarray = new double [10];

Assigning an Array
Array (values) (asign)

double[] myarray = new double[10];
myarray[0] = 1200.0;

Values ( ) Array

100 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

double[] myarray = { 1200.0, 7890.69, 3897.0 };

assign initilize

int[] myarray = new int[5] { 22, 43, 33, 12, 91 };

Array size values


array size values

int[] myarray = new int[5] { 22, 43, 33, 12, 91 };

Array values (elsement) array (copy)


assign target
array assign array size values

int[] myarray = new int[5] { 22, 43, 33, 12, 91 };


int[] myarray2 = myarray;

Array initilize C# compiler array data type default


values array data type
default value 0 bool type

Accessing Array Elements


Array values Array (size) Array
size 10 values 10 values
element element Array Index
(accessing) index

int[] myarray = new int[10];

10 myarray Array
Declear , Initilize
Array Delearation ,assignment

using System;
namespace ArrayApplication
{

101 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10];
/* n is an array of 10 integers */
int i,j;
/* initialize elements of array n */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 1000;
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Using The Foreach Loop


(integer array) n element access for loop
for loop foreach statement Array element
access foreach Array
element

using System;
namespace ConsoleApplication1
{

102 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

class using_the_foreach_loop
{
static void Main(string[] args)
{
int[] n = new int[10];
/* n is an array of 10 integers */
/* initialize elements of array n */
for (int i = 0; i < 10; i++)
{
n[i] = i + 1000;
}
/* output each array element's value */
foreach (int j in n)
{
int i = j - 1000;
Console.WriteLine("Element[{0}] = {1}", i, j);
i++;
}
Console.ReadKey();
}
}
}

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

C# Arrays In Detail
C# Array
Array Multi-dimensional arrays, Jagged
array,Passing arrays to function
Concept Description
Dimension Multi-dimension array C#
Multi-dimensional
Tow-dimensional array
arrays
array

Jagged arrays Multi-dimension array Jagged array C#

103 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Array name Function Parameter Pass


Passing array to
Array Parameter Pass Index
functions

Passing Parameter
Param arrays
Param Array
Array Class Properties Method C# Programmer
The Array Class

C# Multi-dimensional Arrays
Array Array One dimensional
array Multi-dimensional array
Row Coloum Coloum Rows
Multi-dimensional Array
Rectangular array 2 dimensional array

String [ , ] students;

3 dimensional array
String [ , , ] students;

Two-dimensional Arrays
2 dimensional array 2 dimensional
array row coloum Table
row x coloum y
2 dimensional array row 3 coloum 3
(3 3) 9 Array A
Coluom 0 Coluom 1 Coluom 2
Row 0 A[0][0] A[0][1] A[0][2]
Row 1 A[1][0] A[1][1] A[1][2]
Row 2 A[2][0] A[2][1] A[2][2]

2 dimensional array element row,col Index number


access A[0][1] Array row coloum

104 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

element
coloum x Row Coloum

Initializing Two-dimensional Array


Multi- dimensional array Initilize { } (bracket) values
Two- dimensional array I

int [,] A = {
{1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6} , /* initializers for row indexed by 1 */
{7, 9, 10} /* initializers for row indexed by 2 */
};

Assigning Two-dimensional Array


Two- dimensional array element access row coloum index
number A Two-
dimensional array row = 1,colum =1 element
int val = A[1,1];
statement array A row 1,coloum 1 value int val
val A[1,1]
loop statement Two- dimensional array element

using System;

namespace Two_dimensional_Array_Loop
{
class MyArray
{
static void Main(string[] args)
{
/* an array with 5 rows and 2 columns*/
int[,] A = new int[5, 2]
{ { 0, 0 }, { 1, 2 }, { 2, 4 }, { 3, 6 }, { 4, 8 } };
int i, j;
/* output each array element's value */
for (i = 0; i < 5; i++)
{ for (j = 0; j < 2; j++)
{
Console.WriteLine("A[{0},{1}] = {2}", i, j, A[i, j]);

105 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
}
Console.ReadKey();
}
}
}

A[0,0]: 0
A[0,1]: 0
A[1,0]: 1
A[1,1]: 2
A[2,0]: 2
A[2,1]: 4
A[3,0]: 3
A[3,1]: 6
A[4,0]: 4
A[4,1]: 8

Jagged Array
Jagged Array Array Multi- dimensional array
Jagged Array coloum row

int [][] JArray;
Jagged Array Declear coloum

int [][] JArray = new int [5][];


for (int i = 0 ;i < JArray.Length; i++)
{
JArray[i] = new int [4];
}
Jagged Array I
int [][] JArray = new int [2][]{new int[]{12,11,10}, new int[]{100,111,222,333}};
Jagged Array row 2 row coloum 3
row coloum 4 coloum Multi-dimensional
array Jagged

using System;

namespace Jagged_Array
{

106 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

class MyArray
{
static void Main(string[] args)
{
/* a jagged array of 5 array of integers*/
int[][] a = new int[][]{new int[]{0,0},new int[]{1,2}, new int[]{2,4},new
int[]{ 3, 6 }, new int[]{ 4, 8 } };
int i, j;
/* output each array element's value */
for (i = 0; i < 5; i++)
{
for (j = 0; j < 2; j++)
{
Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
}
}
Console.ReadKey();
}
}
}

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

Passing Array to functions


C# Array function

using System;

namespace Passing_arrays_to_functions
{
class MyArray
{

107 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

double getAverage(int[] arr, int size)


{
int i;
double avg;
int sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = (double)sum / size; return avg;
}

static void Main(string[] args)


{
MyArray app = new MyArray();
/* an int array with 5 elements */
int[] balance = new int[] { 100, 32, 13, 117, 150 };
double avg;
/* pass pointer to the array as an argument */
avg = app.getAverage(balance, 5);
/* output the returned value */
Console.WriteLine("Average value is: {0} ", avg);
Console.ReadKey();
}
}
}

Average values is : 82.4

Param Array
Passing Array to fucntions P Array (size)
( )
Passing Param array Param array
param
Array P

using System;

namespace Param_Array
{
class ParamArray

108 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
public int AddElements(params int[] arr)
{
int sum = 0;
foreach (int i in arr)
{
sum += i;
}
return sum;
}
}
class TestClass
{
static void Main(string[] args)
{
ParamArray app = new ParamArray();
int sum = app.AddElements(312, 420, 110, 531, 1889);
Console.WriteLine("The sum is: {0}", sum);
Console.ReadKey();
}
}
}

The sum is : 3262

The Array Class


One dimensional Array, Multidimensional Array, Jagged
Array,Param Array C# Array Class Array Class System
namespace Array Class Array
Method Propertie

Properties of the Array Class

S.N Property Name & Description


IsFixedSize
1
Array Fix Size / Get
IsReadOnly
2
Array Read only / Get
Length
3 Array (size) Get Array size 32-bit integer

109 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

LongLength
4 Array Dimension (size) Get size 64-bit
integer
Rank
5
Array Diemsion Get

Methods of the Array Class


S.N Property Name & Description
Clear();
1 Array element default value Set 0 false
null Array Data type
Copy(Array, Array, Int32) ;
Array Array copy copy
2
source Array index 0 int32 (length)
Distination Array Paste
CopyTo(Array, Int32) ;
3 Current Array Array copy index

GetLength(Int32);
4 Array dimentsion dimentsion length Get
32-bit integer Type
GetLongLength(Int32);
5 Array dimentsion dimentsion length Get
64-bit integer Type
GetLowerBound();
6 Array element Get

GetType();
7
Array Data Type Get
GetUpperBound ();
8 Array element Get

GetValue(Int32) ;
9
index Array element Get
IndexOf(Array, Object) ;
10 Array Object Object
Array Object index
Reverse(Array);
11
Array element

110 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

SetValue(Object, Int32) ;
12
Array index Object Set
Sort(Array) ;
13
Array element
ToString ();
14
Array elemnt string

using System;
namespace Method_Properties
{
class MyArray
{
static void Main(string[] args)
{
int[] list = { 22, 120, 131, 91, 15, 30, 11 };
int[] temp = list; //list.CopyTo(temp, 0);//Array.Copy(list, temp, 5);
Console.WriteLine("Lower Bound :"+list.GetLowerBound(0));
Console.WriteLine("Upper Bound :" + list.GetUpperBound(0));
Console.WriteLine("Type Of Array :" + list.GetType());
Console.Write("Original Array: ");
foreach (int i in list)
{
Console.Write(i + " ");
}
Console.WriteLine();//reverse the array
Array.Reverse(temp);
Console.Write("Reversed Array: ");
foreach (int i in temp)
{
Console.Write(i + " ");
}
Console.WriteLine();//sort the array
Array.Sort(list);
Console.Write("Sorted Array: ");
foreach (int i in list)
{
Console.Write(i + " ");

111 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
Console.ReadKey();
}
}
}

Lower Bound :0
Upper Bound :6
Type Of Array :System.Int32[]
Original Array: 22 120 131 91 15 30 11
Reversed Array: 11 30 15 91 131 120 22
Sorted Array: 11 15 22 30 91 120 131

112 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

String charater , ,3, ,) Array -A


ABC string String String keyword
String keyword System.String

String variable -

String variable variable assign (string firstname;


=Y ;).
String Class Constructor string ( char []
={ , ,Z}; = );).
String class join method String
={H , ,Y ,S , }; S =
S .J , );).
String Class Format method value ( ) object
(DateTime DT= new DateTime(2012,10,10,17,58,1); String
=S .F {0, } { 0,D},D );).

example program String


using System;

namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";

113 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

string fullname = fname + lname;


Console.WriteLine("Full Name: {0}", fullname);

char[] letters = { 'H', 'e', 'l', 'l', 'o' };


string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);

string[] sarray = { "Hello", "From", "Tutorials", "Point" };


string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);

DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);


string chat = String.Format("Message sent at {0:t} on {0:D}",
waiting);
Console.WriteLine("Message: {0}", chat);
Console.ReadKey();
}
}
}

Full Name: Rowan Atkinson


Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012

String Class properties chars

Chars : String charater position charater chars



Length : String charater length

String class M

Methods of the String


No Method Name
1 public static int Compare( string strA, string strB )
String object integer type
2 public static string Concat( string str0, string str1 )
String object Concat
3 public bool Contains( string value )
String charater ( ) string
= I ; .C ){});
4 Public static string Copy( string str )

114 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

String Copy
5 public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count )
6 public bool EndsWith( string value )
string ( ) String object (yannaing)
EndsWith ng String object
(String.EndsWith(string value)).
7 public bool Equals( string value )
Equals String
public static string Format( string format, Object arg0 )
8 Format method
String time=String.Format {0, } { 0,D},D );)
9 public int IndexOf( char value )
String object charater index (string
=H , int index = message.IndexOf('H'); index )
10 public int IndexOf( string value )
String object string index (string
=H F , int index = message.IndexOf(F ); index 5 )
11 public int IndexOfAny( char[] anyOf )
String object charater array index
12 public int IndexOfAny( char[] anyOf, int startIndex )
String object charater array index
startIndex
13 public string Insert( int startIndex, string value )
Insert method string parameter
index parameter
string
14 public static bool IsNullOrEmpty( string value )
String null value E
15 public static string Join( string separator, params string[] value )
String Array string Separator result
space ,
String array [] ={ , };
S . ,, ); result ,
16 public static string Join( string separator, string[] value, int startIndex, int count )
String Array Separator
result ,
String array [] ={ , };
S . ,, ); ,
parameter index parameter

115 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

17 public int LastIndexOf( char value )


String object charater index
=H H, int index = message.IndexOf('H'); index 5 )
18 public string Remove( int startIndex )
String index number index Remove
19 public string Replace( char oldChar, char newChar )
Replace charater

20 public string[] Split( params char[] separator )
Split method string S = , ;
Splite S [] = S .S ,); strarray
array
21 public bool StartsWith( string value )
string ( ) String object (yannaing) StarsWith
ya String object (String.StarsWith(string
value)).
22 public char[] ToCharArray( int startIndex, int length )
23 public string ToLower()
L C ToLower
24 public string ToUpper()
C ToUpper
25 public string Trim()
String - Remove

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mystring
{
class Program
{
static void Main(string[] args)
{

string str1 = "This is test";


string str2 = "This is text";

if (String.Compare(str1, str2) == 0)
{
Console.WriteLine(str1 + " and " + str2 + " are equal.");
}
else
{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");

116 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
Console.ReadKey();
}
}
}

This is test and This is text are not equal.

Contains String Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mystring
{
class Program
{
static void Main(string[] args)
{
string str = "This is test";
if (str.Contains("test"))
{
Console.WriteLine("The sequence 'test' was found.");
}
Console.ReadKey();
}
}
}

The sequence 'test' was found.

Example program SubString

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mystring
{
class Program
{

117 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

static void Main(string[] args)


{
string strsub = "Last night I dreamt of San Pedro";
Console.WriteLine(strsub);
string substr = strsub.Substring(23);
Console.WriteLine(substr); }
}
}

San Pedro

118 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Structure Values Type () class


Variable Group
sturcture Data Type
User defined type structure
Rectangle coordinate characteristices data structure
Structure C# struct keyword
Data Struce

Structure Data Type
-
( )
(attribute)
( )
structure

Defining a Structure
Struct keyword Data Type (structucture)
struct { } struct members

struct Books
{
public string name;
public string author;
public string subject;
public string book_id;
};
Books { } name, author, subject book_id
Books structure member

119 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

struct ;

using System;

struct Books {
public string title;
public string author;
public string subject;
public int book_id;
};
namespace Structures
{
class Program
{
static void Main(string[] args)
{
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "C# Tutorilas";
Book1.author = "Process Group";
Book1.subject = "Programming";
Book1.book_id = 989771;

/* book 2 specification */
Book2.title = "C# Beginner Books";
Book2.author = "Process Group";
Book2.subject = "Programming";
Book2.book_id = 989772;

/* print Book1 info */


Console.WriteLine("Book 1\ntitle : {0}", Book1.title);
Console.WriteLine("author : {0}", Book1.author);
Console.WriteLine("subject : {0}", Book1.subject);
Console.WriteLine("book_id :{0}\n", Book1.book_id);
/* print Book2 info */
Console.WriteLine("Book 2\ntitle : {0}", Book2.title);
Console.WriteLine("author : {0}", Book2.author);
Console.WriteLine("subject : {0}", Book2.subject);
Console.WriteLine("book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}
}

120 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Book 1
Title : C# Tutorials
author : Process Group
subject : Programming
book_id : 989771

Book 2
Title : C# Beginner Books
author : Process Group
subject : Programming
book_id : 989772

Features of C# Structure
Structure Structure Feature

C C++ programming Language structure

C# structure -

Structure Methods, Fields, Indexers, Properties, Operator method Event

Structure Constructors default constructor

construtor defined Destructor

Structures structure class (inheritance)

class

structure class base class



Interface ( ) Interface
Abstract, Virtual Protect Access modifier Structure menber

New Operator struct object
member constructor initialize Class
New Operator struct
New Operator objcet intialize

121 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Class Vs Structure
Class Structure

Class Ref Structure

Structure (inheritance)

Structure default constructor


Books Structure

using System;

struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
public void getValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id = id;
}
public void display()
{
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}\n", book_id);
}
};
namespace Structures
{
class Program
{
static void Main(string[] args)
{
Books Book1 = new Books(); /* Declare Book1 of type Book */
Books Book2 = new Books(); /* Declare Book2 of type Book */
/* books specification */
Book1.getValues("C# Tutorilas", "Process Group", "Programming",
989771);
Book2.getValues("C# Beginner Books", "Process Group", "Programming",
989772);
/* print Books info */
Book1.display();
Book2.display();

122 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.ReadKey();
}
}
}

Title : C# Tutorials
author : Process Group
subject : Programming
book_id : 989771

Title : C# Beginner Books


author : Process Group
subject : Programming
book_id : 989772

123 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Integer Constant Enumerated Type


Enumerated Type enum keyword
Enum values (inherit)

Declaring Enum Variable

enum <enum_name>
{
Enumeration list
};
enum_name enum Enumeration list symbol
Symbol , symbole
integer value Default 0 1,2,3

enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
Enum D Sun Mon Tue Web Thu Fri
Sat Symbol () Symbol Sum Integer Value 0 Mon 1
Tue 2 Integer Value Enum Symbol
symbol Integer Value ( ) Id
Integer Value
Enum

using System;

namespace Enum
{
class Program

124 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main(string[] args)
{
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;

Console.WriteLine("Monday: {0}", WeekdayStart);


Console.WriteLine("Friday: {0}", WeekdayEnd);
Console.ReadKey();
}
}
}

Monday : 1
Friday : 5

125 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Class Data Type Data Type


Class object object
Function object Class
Class member Fuintion member variable Function variable

Class Definition
Class Class Keyword
name Class Body curly braces { } )
Class

<access specifier> class class_name


{
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
<access specifier> <return type> method2(parameter_list)
{
// method body
}
...
<access specifier> <return type> methodN(parameter_list)
{
// method body
}

126 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Class Note
Access specifiers Class Class member Funtion member
variable Class Default Access specifiers
I Class member Funtion member variable
Default Access specifiers
Data type specifies variable return type specifies
function data int fun_Name(){ int s ;s=1; return s }
F Data Type
int Data type
Class member Funtion ( ) member variable dot (.) operator

member Funtion ( ) member variable class
object Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoxApplication
{
class Box
{
public double length; // Length of a box
public double breadth; // Breadth of a box
public double height; // Height of a box
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification

127 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
Console.WriteLine("Volume of Box1 : {0}", volume);

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}

Volume of Box1 : 210


Volume of Box2 : 1560

Member Functions and Encapsulation


Class member function Function class
member variable Class class object
member
Class member variable object attribute ( )
Encapsulation Hide data data Function
property
Encapsulation Member function
Member variable Encapsulation C# Member variable Property

using System;

namespace BoxApplication1
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength(double len)
{
length = len;

128 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
public void setBreadth(double bre)
{
breadth = bre;
}
public void setHeight(double hei)
{
height = hei;
}
public double getVolume()
{
return length * breadth * height;
}
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// Declare Box2 of type Box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);

// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);

Console.ReadKey();
}
}
}

Volume of Box1 : 210


Volume of Box2 : 1560

129 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Constructors in C#
Constructors Class Special M F object
(Create) Constructors executed Object
Constructiors Constructors name
Class name Return type

using System;

namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line()
{
Console.WriteLine("Object is being created");
}

public void setLength(double len)


{
length = len;
}
public double getLength()
{
return length;
}

static void Main(string[] args)


{
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}

Object is being created


Length of line : 6

Constructors Default constructor Parameterized constructors


Default constructor Pararmeter Parameterized constructors Parameter
Object Initial value Parameterized
constructors

130 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;

namespace LineApplication1
{
class Line
{
private double length; // Length of a line
public Line(double len) //Parameterized constructor
{
Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}
public void setLength(double len)
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line(10.0);
Console.WriteLine("Length of line : {0}", line.getLength());
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}

Object is being created, length = 10


Length of line : 10
Length of line : 6

Destructors in C#
Destructors Class F Object close
Destructors executed Destructors name Class Name
~) Program Flie Memory Release
Destructors Destructors Inherit
Overloading Program

131 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;

namespace LineApplication2
{
class Line
{
private double length; // Length of a line
public Line() // constructor
{
Console.WriteLine("Object is being created");
}
~Line() //destructor
{
Console.WriteLine("Object is being deleted");
}

public void setLength( double len )


{
length = len;
}
public double getLength()
{
return length;
}

static void Main(string[] args)


{
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
}
}
}

Object is being created


Length of line : 6
Object is being deleted

Static Members of a C# Class


Class Member Static keyword Static member
Class member static Class Object
Class member static member instant
member Static member class member Instant
member object member Static member

member instant member Static member object


Class member Static Class
member Copy Instant variable

132 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

object variable
object static variable
memory Class name staitic variable
Static member Instant member
instant member Static member Instant
member object name Static member Class name
Static member member function Initial

using System;

namespace StaticVarApplication
{
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum());
Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Console.ReadKey();
}
}
}

Variable num for s1: 6


Variable num for s2: 6
Static member function

133 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;

namespace StaticVarApplication
{
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public static int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s = new StaticVar();
s.count();
s.count();
s.count();
Console.WriteLine("Variable num: {0}", StaticVar.getNum());
Console.ReadKey();
}
}
}

Variable num: 3

134 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Object-oriented programming Inheritance


Class ( ) Member function Member variable Class
inheritance Function
Member variable Member function Class
Class Class
Class Base Class Class Drived Class
Animal Class Member variable

Class Animal
{
string name;
int age;
}
animal class
member variable name age Type
dog class name age animal class
inheritance

Class Dog : Animal


{
String type ;
}
I Animal class Dog
Animal
class Dog class access specifier
C A
) inheritance x

<acess-specifier> class <base_class>


{
}

135 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

class <derived_class> : <base_class>


{
...
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace inheritance
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}

// Derived class
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}

Total area: 35

136 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Base Class Initialization


base class member function Derive class

using System;

namespace RectangleApplication
{
class Rectangle
{
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w)
{
length = l;
width = w;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class Tabletop : Rectangle
{
private double cost;
public Tabletop(double l, double w)
: base(l, w)
{ }
public double GetCost()
{
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display()
{
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Tabletop t = new Tabletop(4.5, 7.5);
t.Display();

137 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.ReadLine();
}
}
}

Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5

Multiple Inheritance in C#
C# Multiple inheritance Multiple inheritance
Interface multiple inheritance
P

using System;

namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}

// Base class PaintCost


public interface PaintCost
{
int getCost(int area);

}
// Derived class
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;

138 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: ${0}", Rect.getCost(area));
Console.ReadKey();
}
}
}

Total area: 35
Total paint cost: $2450

139 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Polymorphism name
One name , Multiple Form (One name , Multiple Form
integer parameter area Function ) Double parameter
area Function ) function name parameter
Data type ) Polymorphism ("having multiple
forms") Polymorphism static polymorphism dynamic polymorphism
Static polymorphism Compile time polymorphism ( )
Early Binding Dynamic polymorphism Run time polymorphism ( ) Late
Binding Polymorphism

Interface polymorphism
Inheritance polymorphism
Polymorphism through abstract classes

Polymorphism

Static Polymorphism Dynamic Polymorphism


(overloading method (virtual method
) )

140 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Static Polymorphism (Compile time polymorphism)

Static Polymorphism Funiction Compile Time Static


Polymorphism Function overloading Operator overloading (Operator Overloading
() ) Function
overloading

Function Overloading
Operator overloading

Function Overloading

F function
F
F F O
D
function overloading function name
Argument ( ) parameter type
Parameter parameter Data type
Function Overloading Program

using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}
void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}

void print(string s)
{

141 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("Printing string: {0}", s);


}
static void Main(string[] args)
{
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C++");
Console.ReadKey();
}
}
}

Total area: 35
Total paint cost: $2450

Dynamic Polymorphism (Runtime polymorphism)

Dynamic Polyrophism Rutime Function


A Dynamic Polymorphism
Base class Base class
Abstract Class Base class Derived Class
inherit Abstract Class abstract method
Abstract method virtual member B Abstract class method
( ) function Derived class method ( ) function
Abstract class abstract class

Abstract class instance class


Abstract method ( ) fuinction Abstract class

using System;

142 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

namespace PolymorphismApplication1
{
abstract class Shape
{
public abstract int area();
}
class Rectangle: Shape
{

private int length;


private int width;
public Rectangle( int a=0, int b=0)
{
length = a;
width = b;
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}", a);
Console.ReadKey();
}
}
}

program execute result

Rectangle class area :

Area: 70

Abstract Class
inherit Runtime virtual
method Function Runtime virtual method
program

143 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;
namespace PolymorphismApplication
{
class Shape
{
protected int width, height;
public Shape( int a=0, int b=0)
{
width = a;
height = b;
}
public virtual int area()
{
Console.WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape
{
public Rectangle( int a=0, int b=0): base(a, b)
{

}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape
{
public Triangle(int a = 0, int b = 0): base(a, b)
{

}
public override int area()
{
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller
{
public void CallArea(Shape sh)
{
int a;
a = sh.area();
Console.WriteLine("Area: {0}", a);

144 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
}
class Tester
{

static void Main(string[] args)


{
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}
}
program execute result

Rectangle class area:


Area: 70
Triangle class area:
Area: 25

145 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Operator Overloading C# built-in Operator


O Programmer operator User-defined
types Overloading Operator Function
Operator Keyword symbol ( + - ) Operator
Overloading Function return type parameter
Operator Overloading program

using System;
namespace OperatorOvlApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box

public double getVolume()


{
return length * breadth * height;
}
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
public static Box operator+ (Box b, Box c)
{

146 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Box box = new Box();


box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}
}
class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
Box Box3 = new Box(); // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);

// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);

// Add two object as follows:


Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
Console.ReadKey();
}
}
}

program execute result


147 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Volume of Box1 : 210


Volume of Box2 : 1560
Volume of Box3 : 5400

Overloadable and Non-Overloadable Operators


Table c# built-in operator Overloading
Operator Operator

Operator Description

+, -, !, ~, ++, -- Unary operators overloading

+, -, *, /, % Binary operators overloading

==, !=, <, >, <=, >= Comparison operators overloading

&&, || Conditional logical operators overloading



+=, -=, *=, /=, %= Assignment operators overloading

=, ., ?:, ->, new, is, sizeof, typeof operators overloading

C# built-in Opreator P

using System;

namespace OperatorOvlApplication1
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public double getVolume()
{
return length * breadth * height;
}
public void setLength( double len )
{
length = len;

148 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}
public static bool operator == (Box lhs, Box rhs)
{
bool status = false;
if (lhs.length == rhs.length && lhs.height == rhs.height
&& lhs.breadth == rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator !=(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length != rhs.length || lhs.height != rhs.height
|| lhs.breadth != rhs.breadth)
{
status = true;
}

return status;
}
public static bool operator <(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length < rhs.length && lhs.height
< rhs.height && lhs.breadth < rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator >(Box lhs, Box rhs)
{
bool status = false;

149 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

if (lhs.length > rhs.length && lhs.height


> rhs.height && lhs.breadth > rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator <=(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length <= rhs.length && lhs.height
<= rhs.height && lhs.breadth <= rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator >=(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length >= rhs.length && lhs.height >= rhs.height && lhs.breadth >=
rhs.breadth)
{
status = true;
}
return status;
}
public override string ToString()
{
return String.Format("({0}, {1}, {2})", length, breadth, height);
}
}
class Tester1
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
Box Box3 = new Box(); // Declare Box3 of type Box
Box Box4 = new Box();
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
//displaying the Boxes using the overloaded ToString():
Console.WriteLine("Box 1: {0}", Box1.ToString());
Console.WriteLine("Box 2: {0}", Box2.ToString());

150 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
// Add two object as follows:
Box3 = Box1 + Box2;
Console.WriteLine("Box 3: {0}", Box3.ToString());
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
//comparing the boxes
if (Box1 > Box2)
Console.WriteLine("Box1 is greater than Box2");
else
Console.WriteLine("Box1 is greater than Box2");
if (Box1 < Box2)
Console.WriteLine("Box1 is less than Box2");
else
Console.WriteLine("Box1 is not less than Box2");
if (Box1 >= Box2)
Console.WriteLine("Box1 is greater or equal to Box2");
else
Console.WriteLine("Box1 is not greater or equal to Box2");
if (Box1 <= Box2)
Console.WriteLine("Box1 is less or equal to Box2");
else
Console.WriteLine("Box1 is not less or equal to Box2");
if (Box1 != Box2)
Console.WriteLine("Box1 is not equal to Box2");
else
Console.WriteLine("Box1 is not greater or equal to Box2");
Box4 = Box3;
if (Box3 == Box4)
Console.WriteLine("Box3 is equal to Box4");
else
Console.WriteLine("Box3 is not equal to Box4");
Console.ReadKey();
}
}
}
program execute result

Box 1: (6, 7, 5)
Box 2: (12, 13, 10)
Volume of Box1 : 210
Volume of Box2 : 1560

151 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Box 3: (18, 20, 15)


Volume of Box3 : 5400
Box1 is not greater tha
Box1 is less than Box2
Box1 is not greater or
Box1 is less or equal t
Box1 is not equal to Bo
Box3 is equal to Box4

152 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Interfaces class Interface method name method


body Class inherit method body
interface class Name Display
method print() (statement) method
body method class finalDisplay class
inherit finalDisplay class Diplay class print() method
C . L B D ) method body Interface class
method class inherit name, return
,parameters C# language multiple inheritance
interface multiple inheritance Interface multiple
inheritance Interface Reference Type Interface
Interface
Interface Constant Field Constructor Destructor Interface
member Static member I
instance class ( object) Interface member method
member variable access specifiers (public ,private)

interface Display {
void Print(); // method name no method body
}
class finalDisplay : Display
{
public void Print()
{
Console.WriteLine("Base Display"); // method body
}
}

Interface class interface keyword


class Interface class access specifiers default
Interface class

153 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

public interface ITransactions


{
// interface members
void showTransaction();
double getAmount();
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InterfaceApplication
{
public interface ITransactions
{
int v;
// interface members
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions
{
private string tCode;
private string date;
private double amount;
public Transaction()
{
tCode = " ";
date = " ";
amount = 0.0;
}
public Transaction(string c, string d, double a)
{
tCode = c;
date = d;
amount = a;
}
public double getAmount()
{
return amount;
}
public void showTransaction()
{
Console.WriteLine("Transaction: {0}", tCode);

154 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("Date: {0}", date);


Console.WriteLine("Amount: {0}", getAmount());
}
}
class Tester
{
static void Main(string[] args)
{
Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}
program execute result

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

155 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Object-oriented Language Namesapces


Namespaces packaging Namespaces class
interface
firsthouse second house

firsthouser
Namesapce
packaging
packaging packaging packaging
packaging
Namesapces

NameSpaces

Class (or)
InterFace

Method (or)
Function

Statement

Namespace firsthouse

156 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
Public class bedroom{}
Public class dinningroom{}
Public class livingroom{}
}
Namespace secondhouse
{
Public class bedroom{}
Public class dinningroom{}
Public class livingroom{}
}
class name
Namespace
Namespace Namespace keyword
syntax

namespace namespace_name
{
// code declarations
}

Namespace

using System;
namespace first_space
{
class namespace_cl
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space
{
class namespace_cl
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
class TestClass

157 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
static void Main(string[] args)
{
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}
program execute result

Inside first_space
Inside second_space

System namespace Program


Console.Writeline Console Class WriteLine
Console Console class system namespace class
using system Program
using system program Class name
program System.Console.WriteLine

using System;
using first_space;
using second_space;

namespace first_space
{
class abc
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}

namespace second_space
{
class efg
{
public void func()
{

158 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("Inside second_space");
}
}
}
class TestClass
{
static void Main(string[] args)
{
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}
}

program execute result

Inside first_space
Inside second_space

Nested Namespaces
Namesapce namespace nested namespace

NameSpaces
First

Namesapce
Second

Method (or)
Function

Statement

159 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;
using first_space;
using first_space.second_space;

namespace first_space
{
class abc
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
namespace second_space
{
class efg
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
}
class TestClass
{
static void Main(string[] args)
{
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}
}
program execute result

Inside first_space
Inside second_space

160 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Preprocessors directives source code (statements) compile Compiler


Preprocessor directives source code
Compiler C# programming
language Preprocessor directives conditional compilation Statements
waring Message error Message
C# porgramming language
Preprocessors directives C,C++ porgramming language directives
Preprocessor directives
Preprocessor directives statement ; )
Preprocessors directies define
program

#define TestMode
Using System ;
Namespace testname
{
Class test
{
}
}

List of Preprocessor Directives in C#


Preprocesssor Directive Description
#define symbol Preprocessor directive (define)
Symbol

#undef symbol define symbol )

161 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

#if symbol[operator symbol] ... #if symbol


conditional directives

#else #if
#elif #else #if
#endif #if
#line [number[file]|hidden] #line file name line number information

Line number statement
options
#line default option hidden option
#error text #error Error ( ) Line
Error Line

statement

#warning text Warning ( ) Line Warning
Line

#pragma warning Compiler Warning
[disable|restore]
'M ' signed but its
warning
#pragma

#region name Statements
#region

#endregion #region
region #endregion

The #define Preprocessor


Symbolic constants #define directive
#define symbol symbol #if
,#else directive
#define PI symbol
Main {} #if PI PI

162 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

#if statements #else


#endif statements

#define PI
using System;

namespace defineSymbol
{
class Program
{
static void Main(string[] args)
{
#if (PI)
Console.WriteLine("PI is Defined!");
#else
Console.WriteLine("PI is not Defined!");
#endif
Console.ReadKey();
}
}
}

PI is Defined!

Conditional Directives

#if conditional directive


#define symbol symbol
conditional directive Conditional directive
#endif Direcitve condition
#if, #elseif directive directive statements
Conditinal directive syntax

#if symbol [operator symbol]...

Syntex S
Operator symb preprocessor

163 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

directives Operator Operator



== (equality)
!= (inequality)
&& (and)
|| (or)
Symbol operator group ( ) Directive
Operator

#define DEBUG
#define VC_V12
using System;

namespace conditionalDirectives
{
class Program
{
static void Main(string[] args)
{
#if (DEBUG && !VC_V12)
Console.WriteLine("DEBUG is Defined!");
#elif (!DEBUG && VC_V12)
Console.WriteLine("VC_V12 is Defined!");
#elif (DEBUG && VC_V12)
Console.WriteLine("DEBUG and VC_V12 are Defined!");
#else
Console.WriteLine("DEBUG and VC_V12 are not Defined!");
#endif
Console.ReadKey();
}
}
}

PI is Defined!

164 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Regular Expressions Language Input Text ( ) string


character pattern( ) .Net framework Regular
Expressions Perl5 Regular Expression Serach/Replace
( / ) Ex
? color colour (Match) colouur Regular
Expressions user input Text Program
user block ( )
programmer Regular Expressions
Regular Expressions


Console.WriteLine(Regex.Match("color",@"colou?r").Success); // True
Console.WriteLine(Regex.Match("colour",@"colou?r").Success); // True
Console.WriteLine(Regex.Match("colouur",@"colou?r").Success); // False
Regular Expressions
Passwords Phone Text Box user Input
Text Ex
(Passwords 8
)
Text Document ( ) Text (pattern) ( )
( Text Document
)
Html Page Tag Textual Data

Regular Expressions System.Text.RegularExpressions
Regular Expressions Type namespace

165 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Regular Expressions Pattern Character Literals,Operators, Constructor


( )

Constructors For Defining Regular Expressions


Categories Regular Expressions
Constructors Group Quantifiers


Character escapes
Character Classes
Anchors
Grouping Constructs
Quantifiers
Backreference Constructs
Alternation Constructs
Substitutions
Miscellaneous Constructs

Character Escapes

Character Escapes Regular Expressions Escapes


Character Special Character /a /n C# programming language
Special Character Regular Expressions \
Character \ charater
( )

Escaped
Description Pattern Matches
Character
\a Bell Character (\u0007) \u in
\a \a
Warning!+\0007u
\ Character class
\b \b{3,} \b\b\b\b in \b\b\b\b
backspace (\u0008)
Name\t Add\t in
\t \ \t or \u0009) (\w+)\t
Name\tAdd\t
Carriage return (\u000D) \r\nHello in
\r \r\n(\w+)
\rHello\nWorld

Vertical Tab (\v or \u000B)


\v [\v]{2,} \v\v\v in \v\v\v

166 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

\f Form feed (\u000C) [\f]{2,} \f\f\f in \f\f\f

\r\n(\w+) \r\nHello in
\n New Line (\u000A)
\r\nHello\nWorld
\e \u001B (Escape) \e \x001B in \x001B
\ Octal value 3 Digit

space Octal value


\nnn \w\040\w a b,b c in a bc d
40 Octal
value 3 Digit
\040
\ Hexadecimal value

space Hex value


\x nn \w\x20\w a b,b c in a bc d
20 Hexadecimal
value \x20

\ Unicode character
Hexadecimal value
\u nnnn \ \w\u0020\w a b,b c in a bc d
Hexadecimal value 4

\ charater
charater
Charater
2+2 Text
+
\+
\ \d\+\d* 2+2 in (2+2) * 3*9
Regular Expressions
charater Escaped


\ Tab

Character Classes

Set of Character ( ) ( ) Text character


Character Classes Character
Classes

167 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

CharacterClas
Description Pattern Matches
s
Character Group
charater [
] character
[character_gr
[rso] r,o,s in process
oup]
[]
Default case-

[^character_group]
[character_group]
[^character_g []
[^rso] p,c,e in process
roup] character
character

character range
character
[first-last] [ - [m-p] o n in don
] m p
character
.
charater
character
ave in have
a.e ate in mate
.
. kd kk in
. character k. donmakdkkobeoeoehq
charater a
charater e


Unicode general categor
P,G in Process
\p{name} \p{Lu}
Group

\p{name}
r,o,c,e,s in
\P{name} P \P{Lu}
Process

\ (word) P,r,o,c,e,s
\w \w
in Pro#cess
\
\W word \W # in Pro#cess

168 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

White-space
\s \w\s o in pro cess

\
white-space Pr,ce,ss in pro
\S \w\S
character cess

decimal
\d \d 4 in Process4u

\D \d \D P,U in P4U

Anchors

( ) Anchors
Expressions Anchros
Search Replace

Assertion Description Pattern Matches
Line ( ) string character
( ) Decimal number
Pro,Gro in
^ ^ ^\w{3}
Process\nGroup\n
\n(new Line)

Line ( ) string
character ( ) Decimal number
$ $ \d{4}$ 2012 in "10-1-2012"
\n(new Line)

^ Line( )
Pro in
\A string Line \A\w{3}
Process\nGroup\n

$ \n (new
\Z line) \d{4}\Z 2012 in 10-1-2012

\Z \n (new
\z \d{4}\z "-333" in "-901-333"
line)
(1),(3),(5),(9)
\G \G\(\d) in
(1)(3)(5)(9)[7](2)(1)
Boundary preview,process in
\b pr\w*\b
( ) preview ofprocess group

169 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group


\b
boundary ends,ender,ends in

\B \B \Bend\w*\b end sends endure lender


e aends

Grouping Constructs

Reguar Expressions ) expression subexpression


Input Text, string ( )
sub-expressions ( ) group Sub-expressions
Input Text banabanagegea (ba)(na)\1\2
pattern Input Text banabana
(ba) (na)
\1 (ba) \2 na
) ) I x banabanagegea
group ba baba group
na group group
baba group group
bana G
C
Grouping Constructs Description Pattern Matches
subexpressions
pattern

(subexpression) \(e)\1 ee in deep
subexpression 1
subexpression
2,3,4
Subexpressions
\ (?<name>\
(?<name>subexpressi
w)\k<name ee in deep
on) <name> >

(((?'Open
Subexpression ((p-r((o-
'\()[^\(\
((c*e))))))
(?<name1 name2> )]*)+((?'
in
subexpression) Close-
((p-r((o-
Open'\))[
((c*e)))))) (s+s
^\(\)]*)+

170 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

)*(?(Open
)(?!))$

ReadLine,Read,
Read in "
Read(?:Li
<?:subexpression> ne)?
Console.ReadLine()
Console.ReadKey()
Console.Read()
(?imnsx- Supexpressions
"A31xl",A31XL
A\d{2}(?i
imnsx:subexpression (applies, in
:\w+) "A31xl A31XL a12xl "
) disable)

is,ran,out in
He is. The dog
(?=subexpression) \w+(?=\.)
ran. The
sun is out.

sure,used in
\b(?!un)\
(?!subexpression) unsure sure unity
w+\b
used

96,80,15
(?<=19)\d in
(?<=subexpression) {2}\b 1819 1996 1980
1915 2013
44,77,11
(?<!12)\d In
(?<!subexpression) {2}\b 1200 1211 1344
1377 2011

1ABB,3ABB,5AB
[13579](?
(?>subexpression) in 1ABB 3ABBC 5AB
>A+B+)
5AC

Quantifiers

Element (Character Group Character Class)


Regular Expressions Quantifiers
Pattern A + + quantifier
( ) Input string
A A Quantifier

Quantifier Description Pattern Matches
* Z M
* \d*\.d .2,24.9,419.8
Element

171 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

( )
Apple
peo p*
pp p
+ (?<name>\
bel in belle
+ Element ( ) w)\k<name
be in beat
bal+

?
Element
? bea?t beat , bet
( )

Element
,886 in 1,8860
832 ,523 ,256
{n} ,\d{3} in
{ } 1,832,523,256,


Element {
}
"21349 ,12 ,89
{n,} \d{2,}
,593324


{n,m}
{n,m} \d{2,4} "213 ,12 ,89 ,5933

* *
Element Zero or More Time
?
Z O
\ * \d
12.34,1.124,.2
decimal 13 in
*? \d*?\.\d*
* decimal 12.34\n1.124\n.213
,123

12.3 12
) 12. \d*?\.
patten
)
*? + 12.34,1.124 in
+? \d+?\.\d* 12.34\n1.124\n.213
Element One or More Time ,123

172 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

*? ? 2.34,1.124,.213
in
?? Element \d??\.\d*
12.34\n1.124\n.213
Zero or One Time ,123
,876,,543,,210
{n}? {n} ,\d{3}? in
9,876,543,210,
{n,} n 176,683,123
{n,}? ,\d{3,5}?
( ) in 17668312321
176,686,193,
024,123
{n,m} n in
{n,m} \d{3,5}? 17668312
( ) 193024
123
21

Backreference Constructs

Sub-Expressions ( )
sub-expressions
Backreference C \1\2 ( )
Regular Expressions
Backreference
Description Pattern Matches
Constructs
Sub-expressions
\1,\2,\3
sub-
expressions (match
value) PR4R4D in
\number (\w)(\d)\1\2
R4R4
sub-expressions \1
sub-expressions


Sub-expressions
(?'name1'\w)
(?'name2'\d) PR4R4D in
\k<name>
\k<name1>\k< R4R4
name2>

173 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Alternation Constructs

(either/or)
Alternation Constructs
Regular Expressions Alternation Constructs

Alternation
Description Pattern Matches
Construct
element
the,this in this is
| ) | th(is|e|at)
the day

Expression
pattern (?(B)B\d{2} B50,910 in
(?(expression
\b | (?(B)B\d{2}\b|\b\d{3}\b)
)yes|no) no \b\d{3}\b)

(?(expression)yes|no) Baby.jpg,"Car
(?<quoted>"
Expression packing.jpg"
(?(name)yes|n )?(?(quoted
in
o) Back reference ).+?"|\S+\s
Baby.jpg "Car
)
packing.jpg"

Substitution

Regular Expressions Prttern




Character Repacement Inupt Result
Description Pattern
pattern string string
Group construct

substring \b(\w+)(\s)
$3$2$1
$number (\w+)\b one two two one

\b(?<
word1>\w+)(
substring ${word2}
\s)(?<
${name} ${word1} one two two one
word2>\w+)\
b

174 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

L $ \b(\d+)\s?U
$$ SD $$$1 103 USD $103

substitutes (\$*(\d*(\.
**$& "$1.30" "$1.30"
$& +\d+)?){1})

Input
$` string B+ $` AABBCC AAAAC

Input
string
$ B+ $ AABBCC AACCCC

$+ Group B+(C+) $+ AABBCCDD AACCDD


Input string
AAAABBCCCC
$_ B+ $_ AABBCC

Miscellaneous construct
Construct Description Example
P \bA(?i)b\w+\b matches "ABA",
(?imnsx-imnsx) case "Able" in "ABA Able Act"
insensitivity
Regular Expressions inline \bA(?#Matches words starting
(?#comment) comment with A)\w+\b

Regular Expressions X-mode (?x)\bA\w+\b#Matches words
#[to end to line] comment starting with A

175 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

The Regex Class

S.N Methods & Description


1 public static bool IsMatch(string input, string pattern)
Pattern (input string)
False

2 public bool IsMatch(string input,int startat)
Pattern input string(startat input string
)
False

3 public static bool IsMatch(string input, string pattern, RegexOptions options)
public static bool IsMatch(string input, string pattern) xO
Options IgnoreCase, Compiled, Multiline, Singleline ,None

4 public MatchCollection Matches( string input )
Regular Expressions (Matches)
Collection
5 public string Replace( string input, string replacement )
Input string Pattern replace ( )

6 public string[] Split(string input )
Regular Expressions input string Pattern
string array
Regular Expressions

using System;
using System.Text.RegularExpressions;

namespace RegularExp1
{
class Program
{
private static void showMatch(string text, string expr)
{
Console.WriteLine("Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);

176 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

foreach (Match m in mc)


{
Console.WriteLine(m);
}
}
static void Main(string[] args)
{
string str = "A Thousand Splendid Suns";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}

Matching words that start with 'S':


Expression: \bS\S*
Splendid
Suns



using System;
using System.Text.RegularExpressions;

namespace RegularExp2
{
class Program
{
private static void showMatch(string text, string expr)
{
Console.WriteLine("Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc)
{
Console.WriteLine(m);
}
}
static void Main(string[] args)
{
string str = "make maze and manage to measure it";
Console.WriteLine("Matching words start with 'm' and ends with 'e':");
showMatch(str, @"\bm\S*e\b");
Console.ReadKey();
}
}
}

177 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Matching words start with 'm' and ends with 'e':


The Expression: \bm\S*e\b
make
maze
manage
measure

Input string Pattern



using System;
using System.Text.RegularExpressions;

namespace RegularExp3
{
class Program
{
static void Main(string[] args)
{
string input = "Hello World ";
string pattern = "\\s+";
string replacement = "#";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
Console.ReadKey();
}
}
}

Original String: Hello World


Replacement String: Hello#World#

178 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Program

.. C# C#
programming language Exception Handling
C# Exception Handling
Program User double type User
double variable User double
type ( 1.5 ) string
Runtime Error
Exception Handling try { } Handling
statement ( statements) Error
catch{ } statement
try Error catch Error
catch(Exception ex)

C# Exception Handling try, catch, finally, throw ()

try : Handling ( ) Error statements try block (try {
}) Error try block
statements active ( )
Error try block
catch block catch block
statements
catch : try block statements Error
catch block Exception
catch block Error
(Handle) catch block

179 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

finally : Exception Handle Error


finally block
finally block statements
Exception Handling
throw : catch block throw keyword
Error ( )
catch exception /

Ex H Handle
code try block catch block exception
e1 catch block code 2, 3,,
finally block code try/catch
switch case exception
x catch block
finally block
try
{
// statements causing exception
}
catch (ExceptionName e1)
{
// error handling code
}
catch (ExceptionName e2)
{
// error handling code
}
catch (ExceptionName eN)
{
// error handling code
}
finally
{
// statements to be executed
}

180 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

The Exception Classes in C#

Exception C# class Exception class


class S .Ex Exception class
Exception class
Excepti Exception
exception

Exception Class Description


System.IO.IOException I/O (Input/Output) Error

System.IndexOutOfRangeE Array index


xception Error
System.ArrayTypeMismatc Array Error
hException
System.NullReferenceExc N objcet Error
eption
System.DivideByZeroExce
Zero Error
ption
System.InvalidCastExcep
Tape cation error
tion
System.OutOfMemoryExcep F M ) (Error)
tion
System.StackOverflowExc Variable type
eption Error

Handling Exceptions

Exception try catch block try


block ( ) statements try
block statements Error H
statements catch block program
0 ) Handle

using System;

namespace dividingByZero

181 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int n1, int n2)
{
try
{
result = n1 / n2;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Exception caught: {0}", ex);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers D = new DivNumbers();
D.division(389, 0);
Console.ReadKey();
}
}
}

Exception caught: System.DivideByZeroException: Attempted to divide by zero.


at ...
Result: 0

Creating User-Defined Exceptions

catch block own


exceptions User defined exception
ApplicationException class drived own exceptions

using System;

182 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

namespace UserDefinedExceptions
{
class TemperatureClass
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException ex)
{
Console.WriteLine("TempIsZeroException: {0}", ex.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message){}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if (temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature Found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}

TempIsZeroException: Zero Temperature Found

183 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Throwing
Objects
System.Exception class drived ( ) object
catch block Throw ( ) Throw statement Throw
( )

catch (Exception ex)


{
...
throw ex;
}
Throw Exception
; catch block Exception - )

using System;
namespace Throw_statement
{
class Program
{
static void Main(string[] args)
{
int num1, num2, result;

Console.WriteLine("Enter First Number");


num1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter Second Number");


num2 = Convert.ToInt32(Console.ReadLine());

try
{
try
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
}
catch (DivideByZeroException e)
{
throw;
}
}
catch (Exception e)
{

184 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("Error : " + e.ToString());


}
Console.ReadLine();
}
}
}

Enter First Number


9
Enter Second Number
0
Error : System.Exception: Can't Divide by Zero Exception at
Throw_statement.Program.Main(String[] args) in c:\Users\Yanku-Pc\Documents \Visual
Studio 2012\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:line 21
Ref :http://www.completecsharptutorial.com/basic/throw.php

185 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

File Data H D
name directory path name File read
write File
stream Stream Read input
Stream(read operation) write outStream(write operation)
stream Architecture

Stream Adapter Decorator Streams Backing Store


streams
StreamReader

StreamReader

StreamWriter Deflate Stream File Stream

Byte Byte
BinaryReader Gzip Stream IsolatedStorag
e Stream
BinaryWriter Crypto Stream
MemoryStream

XmlReader Buffered Stream

Network Stream
Xmlwriter

StringReader

StringWriter

186 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# I/O Classes

System.IO namespace file operation class


file create File delete operation
File read write close operation system.io
System.io namespace class

I/O Description
BinaryReader Binary data read
BinaryWriter Binary data write
BufferedStream BufferedStream stream data read write

Directory Directory Directory
( )
DirectoryInfo Directory information

DriveInfo Drive information

File File File ( )

FileStream File data write read FileStream

MemoryStream M data read write
Path Path information
( path.Combine(dir,file))
StreamReader Stream data
StreamWriter Stream data write
StringReader String Buffer( string or stringbuilder) data read

StringWriter String Buffer ( string or stringbuilder) data write

The FileStream
Class
System.IO class Filestream
Filestream stream class File open
Filestream Filestream

187 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

FileStream <object_name> = new FileStream( <file_name>,


<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);

Filestream object F
file .x file mode FileAccess File read
FileShare read write

FileStream F = new FileStream("sample.txt", FileMode.Open,


FileAccess.Read,FileShare.Read);

FileStream parameter

Parameter Description
FileMode FileMode File open method

Append : Append FileMode File File
data File
data write
Create: file
File name File
Auto overwritten
CreateNew: CreateNew Operation System File

File name File
CreateNew
File

Open: file open
OpenOrCreate: OpenOrCreate operation System File open
file
Truncate: Truncate file open S 0

FileAccess FileAccess member () Read,ReadWrite ,Write
FileShare FileShare member ()

188 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Inheritable: FileShare Inheritable File inheritance


child process
None: None current file Share
Read: File read open
ReadWrite: File read write open

Write: File write open

using System;
using System.IO;

namespace FileIOApplication
{
class Program
{
static void Main(string[] args)
{
FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate,
FileAccess.ReadWrite);

for (int i = 1; i <= 20; i++)


{
F.WriteByte((byte)i);
}

F.Position = 0;

for (int i = 0; i <= 20; i++)


{
Console.Write(F.ReadByte() + " ");
}
F.Close();
Console.ReadKey();
}
}
}

program execute result

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1

189 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Reading From And Writing into Text


Files
Text File data Read write StreamReader StreamWirte class
StreamReader StreamWirte Class Stream class
inheritance Files Stream data read write
StreamReader Class

StreamReader Class
StreamReader class TextReader class inheritance text reader
StreamReader member method

S.N Method Name & Purpose


1 public override void Close()
Close method system resources
2 public override int Peek()
Peek method file charater integer (using
(TextReader reader = File.OpenText ("test.txt"))
.P ) > 1) )

3 public override int Read()


Read method stream data charater

program J .x
file data code

using System;
using System.IO;

namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:/jamaica.txt"))

190 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}

StreamWriter Class
StreamWriter class TextWiter class inheritance text write
StreamWriter

S.N Method Name & Purpose


1 public override void Close()
Close method system resources

2 public override void Flush()
Write data Flush()
B data stream
3 public virtual void Write(bool value)
Stream bool value x write
4 public override void Write( char value )
Stream charater write
5 public virtual void Write( decimal value )
Stream decimal value text write
6 public virtual void Write( double value )
Stream double value x write
7 public virtual void Write( int value )
Stream integer value text write
8 public override void Write( string value )

191 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Stream string text write


9 public virtual void WriteLine()
Stream text write

using System;
using System.IO;

namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[] {"Zara Ali", "Nuha Ali"};
using (StreamWriter sw = new StreamWriter("names.txt"))
{
foreach (string s in names)
{
sw.WriteLine(s);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("names.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}

program execute result

Zara Ali
Nuha Ali

192 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Reading From And Writing into Binary


Files
Text File data read write
Binary file Binary file data read write
BinaryReader BinaryWriter

The BinaryReader Class


BinaryReader Class binary file data read
BinaryReader object filestream
constructor BinaryReader b = new BinaryReader(new
F . ));

S.N Method Name & Purpose


1 public override void Close()
Close method B file

2 public virtual int Read()
Read () Method Stream data current position read
3 public virtual bool ReadBoolean()
Stream bool value read ( var r =new
BinaryReader(stream ); bool a = r.ReadBoolean();
4 public virtual byte ReadByte()
Stream data byte read
5 public virtual byte[] ReadBytes( int count )
Stream data byte [] Readsbytes Method
byte ( byte [] br= new
BinaryReader(s).ReadBytes((int) s.Length));
6 public virtual char ReadChar()
Stream data charater Read Charater

7 public virtual char[] ReadChars( int count )
Stream data charater Read Charater[]

8 public virtual double ReadDouble()
Stream 8 byte floating value read
9 public virtual int ReadInt32()
Stream 4 byte integer value read
10 public virtual string ReadString()
Stream strin data read

193 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

The BinaryWriter Class


BinaryWriter Class binary file data write
BinaryWriter object filestream
constructor BinaryWriter b = new BinaryWriter (new
F . ));

S.N Method Name & Purpose


1 public override void Close()
Close method stream
2 public override void Flush()
Write data Flush()
B data stream
3 public virtual long Seek( int offset, SeekOrigin origin )
Seek method write ( ) position write method
( r.seek(0,seekorigin.end)
4 public virtual void Write( bool value )
Stream Boolean value byte write false 0 true 1

5 public virtual void Write( byte value )
Stream unsigned value byte write
6 public virtual void Write( byte[] buffer )
Stream byte array write
7 public virtual void Write( char ch )
Stream Unicode character write
8 public virtual void Write( char[] chars )
Stream Unicode character array write

9 public virtual void Write( double value )
Stream 8 byte floating value write
10 public virtual void Write( int value )
Stream 4 byte integer value write
11 public virtual void Write( string value )
Stream string text write
BinaryReaders BinarWriter class read/write method
program

using System;
using System.IO;

194 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

namespace BinaryFileApplication
{
class Program
{
static void Main(string[] args)
{
BinaryWriter bw;
BinaryReader br;
int i = 25;
double d = 3.14157;
bool b = true;
string s = "I am happy";
//create the file
try
{
bw = new BinaryWriter(new FileStream("mydata",FileMode.Create));
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot create file.");
return;
}
try
{
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot write to file.");
return;
}
bw.Close();
//reading from the file
try
{
br = new BinaryReader(new FileStream("mydata",
FileMode.Open));
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot open file.");
return;
}
try
{
i = br.ReadInt32();
Console.WriteLine("Integer data: {0}", i);
d = br.ReadDouble();

195 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("Double data: {0}", d);


b = br.ReadBoolean();
Console.WriteLine("Boolean data: {0}", b);
s = br.ReadString();
Console.WriteLine("String data: {0}", s);
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot read from file.");
return;
}
br.Close();
Console.ReadKey();
}
}
}

program execute result

Integer data: 25
Double data: 3.14157
Boolean data: True
String data: I am happy

The DirectoryInfo
Class
DirectoryInfo FileSystemInfo inherit inherit
DirectoryInfo Diectory I
copy Diectory method properties
DirectoryInfo properties

S.N Property Name & Description


1 Attributes
Arributes file ( ) directory arttributes
2 CreationTime
file ( ) directory Create Time
3 Exists
Directory Exists
4 Extension
file extension
5 FullName
File ( ) Directory path name

196 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

6 LastAccessTime
File ( ) Directory Time
7 Name
Directory name
DirectoryInfo method

S.N Method Name & Description


1 public void Create()
Directory Create Method
2 public DirectoryInfo CreateSubdirectory( string path )
Subdiectory CreateSubdirectory
3 public override void Delete()
Directory Delete
4 public DirectoryInfo[] GetDirectories()
Directory Subdirectory
5 public FileInfo[] GetFiles()
Directory file list

The FileInfo Class

FileInfo FileSystemInfo inherit inherit


FileInfo File Information
copy File read/write File method
properties FileInfo properties

S.N Property Name & Description


1 Attributes
Arributes file arttributes
2 CreationTime
file Create Time
3 Exists
File Exists
4 Extension
File extension
5 FullName
File path name
6 LastAccessTime
File Time
7 Name
File name

197 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

8 Directory
file Directory
9 LastWriteTime
File write
10 Length
File size
FileInfo method

S.N Method Name & Description


1 public FileStream Create()
File Create Method
2 public StreamWriter AppendText()
File streamWriter text

3 public override void Delete()
File Delete
4 public void MoveTo( string destFileName ) File
New File name

5 public FileStream Open( FileMode mode )
Open File open F M
6 public FileStream Open( FileMode mode, FileAccess access )
Open File open FileMode FileAccess
FileAacess File read write
readwrite
7 public FileStream Open( FileMode mode, FileAccess access, FileShare share )
Open File open FileMode FileAccess
FileAacess File read write
readwrite FileShare file share

8 public FileStream OpenRead()
Filesteam read-only
9 public FileStream OpenWrite()
Filesteam write-only

using System;
using System.IO;

namespace WindowsFileApplication
{
class Program

198 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
static void Main(string[] args)
{
//creating a DirectoryInfo object
DirectoryInfo mydir = new DirectoryInfo(@"c:\Windows");

// getting the files in the directory, their names and size


FileInfo[] f = mydir.GetFiles();
foreach (FileInfo file in f)
{
Console.WriteLine("File Name: {0} Size: {1}",
file.Name, file.Length);
}
Console.ReadKey();
}
}
}

program execute result

File Name: ODBCINST.INI Size: 537


File Name: PFRO.log Size: 11628
File Name: Professional.xml Size: 15841

199 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Atrribute Class Element

System Information ( )

Information Attribute Element assembly,

class, constructor, delegate, enum, event, field, interface, method, portable executable file module,

parameter, property, return value, struct, or another attribute Arribute

Metadata information Program

data Process Run Time Metadata

Net.Framework Attribute () pre-defined arrtirbutes

() custom built attributes

Predefined Attributes
Pre-defined Attributes ()
AttributeUsage
Conditional
Obsolete

ArributeUsage
Custom attribute class Custom attribute class
Element AttibuteUsage
Custom
attribute class inherited Element
custom attribute class Syntax

[AttributeUsage(

200 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

validon, AllowMultiple=allowmultiple,
Inherited=inherited
)]

Validon parameter Element ( )


( ) default value
Element Element
Allowmultiple parameter Optional
vaule B
Default F -
Inherited parameter B Default F

example program AttributeUsage

[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Feild |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // Multiuse attribute.
]
public class Author : System.Attribute
{
string name;
public double version;
public Author(string name)
{
this.name = name;
// Default value.
version = 1.0;
}

public string GetName()


{
return name;
}
}

201 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// Class with the Author attribute.


[Author("P. Ackerman")]
public class FirstClass
{
// ...
}
// Class without the Author attribute.
public class SecondClass
{
// ...
}
// Class with multiple Author attributes.
[Author("P. Ackerman"), Author("R. Koch", version = 2.0)]
public class ThirdClass
{
// ...
}
class TestAuthorAttribute
{
static void Test()
{
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));
}
private static void PrintAuthorInfo(System.Type t)
{
System.Console.WriteLine("Author information for {0}", t);
//Using reflection.
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);
//Reflection.
// Displaying output.
foreach (System.Attribute attr in attrs)
{
if (attr is Author)
{
Author a = (Author)attr;
System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version);
}
}
}
}
program execute result

Author information for FirstClass


P. Ackerman, version 1.00
Author information for SecondClass
Author information for ThirdClass
R. Koch, version 2.00
P. Ackerman, version 1.00

202 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Conditional
Predefined attribute Conditional method process execute
process execute
Debug ( ) Release Method Conditional
attribute debug ( ) Trace Method
Conditional Conditional attribute
Conditional attribute

[Conditional(
conditionalSymbol
)]

#define DEBUG
using System;
using System.Diagnostics;
public class Myclass
{
[Conditional("DEBUG")]
public static void Message(string msg)
{
Console.WriteLine(msg);
}
}
class Test
{
static void function1()
{
Myclass.Message("In Function 1.");
function2();
}
static void function2()
{
Myclass.Message("In Function 2.");
}
public static void Main()
{
Myclass.Message("In Main function.");
function1();
Console.ReadKey();
}
}

203 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

program execute result

In Main function
In Function 1
In Function 2

Absolete
Element ( ) Method information program
Absolete Program Element ( )
Method absolete Class New Method
Old Method
abosolete Old Method New Method warning information
Abosolete

[Obsolete(
message
)]
[Obsolete(
message,
iserror
)]

Obsolete Parameter Obsolete Parameter


Parameter message
Information("Don't use OldMethod, use NewMethod instead")
Parameter iserror B Complier error message
F warning message

using System;
public class MyClass
{
[Obsolete("Don't use OldMethod, use NewMethod instead", true)]
static void OldMethod()
{
Console.WriteLine("It is the old method");

204 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
static void NewMethod()
{
Console.WriteLine("It is the new method");
}
public static void Main()
{
OldMethod();
}
}

program execute result

Don't use OldMethod, use NewMethod instead

Custom Attributes

Net.Framework Custom Arrtributes


Custom Attributes Run Time information
Custom Attributes information
Element ArrituteUsage Element Element
ArrtibuteUsage Custom Attributes
() ()

Declaring a custom attribute
Constructing the custom attribute
Apply the custom attribute on a target program element
Accessing Attributes Through Reflection
Accessing Attribute Through Reflection Reflection
Metadata information ( ) Data
Reflection Arribute Metadata information
Metadata

Declaring a Custom Attribute

205 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Custom Attribute Arritbute Declar


Attribute Class System.Attribute inherit

[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : System.Attribute

Constructing the Custom Attribute


Debuginfo class system.Arrtibute inherit
Construct Custom Attribute Debuginfo class Debuging data
Program
Debuging information
Code number ( ) ID
Developer
Date
Developer Remark
program Debuginfo class private properties () public properties
code number( ) ID , Developer Date
message Attribute
Constructor parameter constructor pass
program

//a custom attribute BugFix to be assig


[AttributeUsage(AttributeTargets.Class
AttributeTargets.Constructor |

AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo : System.Attribute


{
private int bugNo;
private string developer;
private string lastReview;

206 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

public string message;


public DeBugInfo(int bg, string dev, string d)
{
this.bugNo = bg;
this.developer = dev;
this.lastReview = d;
}
public int BugNo
{
get
{
return bugNo;
}
}
public string Developer
{
get
{
return developer;
}
}
public string LastReview
{
get
{
return lastReviw;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}

Applying the Custom Attribute


Attribute Declar Construct
Program Attribute
Reflection Reflection
program

207 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]


[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
class Rectangle
{
//member variables
protected double length;

protected double width;


public Rectangle(double l, double w)
{
length = l;
width = w;
}
[DeBugInfo(55, "Zara Ali", "19/10/2012",
Message = "Return type mismatch")]
public double GetArea()
{
return length * width;
}
[DeBugInfo(56, "Zara Ali", "19/10/2012")]
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}

208 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Runtime Information Reflection


attributes Element Reflection
Element attributes System.Reflection
metadata Runtime
System.Reflection application type
(object type, Interger Type) Runtime
class

Using The Reflection

Runtime attributes Inforamtion


Assembly type instance type

Runtime Method properties
System.Reflection MemberInfo metadata information
System.Reflection attribute
Attribute class
attribute attribute attribute information
System.Reflection Program

System.Reflection.MemberInfo info = typeof(MyClass);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
[AttributeUsage(AttributeTargets.All)]

209 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

public class HelpAttribute : System.Attribute


{
public readonly string Url;
public string Topic // Topic is a named parameter
{
get
{
return topic;
}
set
{
topic = value;
}
}
public HelpAttribute(string url) // url is a positional parameter
{
this.Url = url;
}
private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass
{
}
class Program
{
static void Main(string[] args)
{
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
System.Console.WriteLine(attributes[i]);
}
Console.ReadKey();
}
}
}

Program Run Custom Attribute

HelpAttribute

Attribute DeBugInfo attribute


System.Reflection Program

210 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;
using System.Reflection;
namespace BugFixApplication
{
//a custom attribute BugFix to be
//assigned to a class and its members
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : System.Attribute
{
private int bugNo;
private string developer;
private string lastReview;
public string message;
public DeBugInfo(int bg, string dev, string d)
{
this.bugNo = bg;
this.developer = dev;
this.lastReview = d;
}
public int BugNo
{
get
{
return bugNo;
}
}
public string Developer
{
get
{
return developer;
}
}
public string LastReview
{
get
{
return lastReview;
}
}
public string Message
{
get
{

211 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

return message;
}
set
{
message = value;
}
}
}
[DeBugInfo(45, "Zara Ali", "12/8/2012",
Message = "Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012",
Message = "Unused variable")]
class Rectangle
{
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w)
{
length = l;
width = w;
}
[DeBugInfo(55, "Zara Ali", "19/10/2012",
Message = "Return type mismatch")]
public double GetArea()
{
return length * width;
}
[DeBugInfo(56, "Zara Ali", "19/10/2012")]
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(4.5, 7.5);
r.Display();
Type type = typeof(Rectangle);
foreach (Object attributes in type.GetCustomAttributes(false))
{
DeBugInfo dbi = (DeBugInfo)attributes;
if (null != dbi)
{
Console.WriteLine("Bug no: {0}", dbi.BugNo);
Console.WriteLine("Developer: {0}", dbi.Developer);
Console.WriteLine("Last Reviewed: {0}",
dbi.LastReview);

212 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("Remarks: {0}", dbi.Message);


}
}

//iterating through the method attribtues


foreach (MethodInfo m in type.GetMethods())
{
foreach (Attribute a in m.GetCustomAttributes(true))
{
DeBugInfo dbi = (DeBugInfo)a;
if (null != dbi)
{
Console.WriteLine("Bug no: {0}, for Method: {1}",
dbi.BugNo, m.Name);
Console.WriteLine("Developer: {0}", dbi.Developer);
Console.WriteLine("Last Reviewed: {0}",
dbi.LastReview);
Console.WriteLine("Remarks: {0}", dbi.Message);
}
}
}
Console.ReadLine();
}
}
}
Program Run Result

Length: 4.5
Width: 7.5
Area: 33.75
Bug No: 49
Developer: Nuha Ali
Last Reviewed: 10/10/2012
Remarks: Unused variable
Bug No: 45
Developer: Zara Ali
Last Reviewed: 12/8/2012
Remarks: Return type mismatch
Bug No: 55, for Method: GetArea
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks: Return type mismatch
Bug No: 56, for Method: Display
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks:

213 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Properties Class structures interfaces member name class


member variable member method Fields Properties field
x Properties Member variable privte accessor
private member variable class
properties Properties
public properties datatype
Properties value set keyword value get keyword
Properties member variable member variable properties
private variable properties

// Declare a Code property of type string:


public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
// Declare a Name property of type string:
public string Name
{
get
{
return name;
}

214 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

set
{
name = value;
}
}
// Declare a Age property of type int
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}

using System;
class Student
{

private string code = "N.A";


private string name = "not known";
private int age = 0;
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
// Declare a Name property of type string:
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}

215 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// Declare a Age property of type int:


public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public override string ToString()
{
return "Code = " + Code + ", Name = " + Name + ", Age = " + Age;
}
public static void Main()
{
// Create a new Student object:
Student s = new Student();
// Setting code, name and the age of the student
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info: {0}", s);
//let us increase age
s.Age += 1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}
}

Student Info: Code = 001, Name = Zara, Age = 9


Student Info: Code = 001, Name = Zara, Age = 10

Abstract Properties

Abstract class Properties Properties


Abstract properties Abstract class
Properties name Propertes body (Properties name properties body method
name method body () interface class ) drives
class override program

216 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;
public abstract class Person
{
public abstract string Name
{
get;
set;
}
public abstract int Age
{
get;
set;
}
}
class Student : Person
{

private string code = "N.A";


private string name = "N.A";
private int age = 0;

// Declare a Code property of type string:


public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
// Declare a Name property of type string:
public override string Name
{
get
{
return name;
}
set
{
name = value;
}
}
// Declare a Age property of type int:
public override int Age
{
get

217 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
return age;
}
set
{

age = value;
}
}
public override string ToString()
{
return "Code = " + Code + ", Name = " + Name + ", Age = " + Age;
}
public static void Main()
{
// Create a new Student object:
Student s = new Student();

// Setting code, name and the age of the student


s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info:- {0}", s);
//let us increase age
s.Age += 2;
Console.WriteLine("Student Info:- {0}", s);
Console.ReadKey();
}
}

Student Info: Code = 001, Name = Zara, Age = 9


Student Info: Code = 001, Name = Zara, Age = 11

218 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Indexers class Array


Class indexers Class virtual Array
Indexers calss object
object data [ ] ( A
=A ); [0]= ;)

element-type this[int index]


{
// The get accessor.
get
{
// return the value specified by index
}

// The set accessor.


set
{
// set the value specified by index
}
}
Indexers Indexers
properties Indexers accessors
datatype Indexers value set keyword
value get keyword Properites properties name
Indexer name Indexers
program

219 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index] // indexes
{
get
{
string tmp;

if (index >= 0 && index <= size - 1)


{
tmp = namelist[index];
}
else
{
tmp = "";
}

return (tmp);
}
set
{
if (index >= 0 && index <= size - 1)
{
namelist[index] = value;
}
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";

220 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

for (int i = 0; i < IndexedNames.size; i++) //size class


size static static object

{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.

Overloaded Indexers

Indexers overloaded Overloading function name type


overloading parameter overloading
Indexers Overloading interger type string type overloaded

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace indexer
{
class IndexedNames1
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames1()
{
for (int i = 0; i < size; i++)
{
namelist[i] = "N. A.";

221 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
}
public string this[int index]
{
get
{
string tmp;

if( index >= 0 && index <= size-1 )


{
tmp = namelist[index];
}
else
{
tmp = "";
}
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
public int this[string name]
{
get
{
int index = 0;
while(index < size)
{
if (namelist[index] == name)
{
return index;
}
index++;
}
return index;
}

}
static void Main(string[] args)
{
IndexedNames1 names1 = new IndexedNames1();
names1[0] = "Zara";
names1[1] = "Riz";
names1[2] = "Nuha";
names1[3] = "Asif";
names1[4] = "Davinder";
names1[5] = "Sunil";

222 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

names1[6] = "Rubic";
//using the first indexer with int parameter
for (int i = 0; i < IndexedNames1.size; i++)
{
Console.WriteLine(names1[i]);
}
//using the second indexer with the string parameter
Console.WriteLine(names1["Nuha"]);// Indexer string type overloaded
Console.ReadKey();
}
}
}

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
2

223 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Delegates Delegates Delegates


system.Delegates Delegates reference type
pointer function Delegates event
call-back method method
call-back method Delegates Delegates
method method class Delegates
Delegates Runtime Delegates
parameter Return type

delegate int NumberChanger(int n);// delegate


public static int AddNum(int p) // method
{
num += p;
return num;
}
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum); //delegate method
pass
nc1 (4);

Declaring Delegates

Delegates Delegates keywoard Return type


Delegates name (public delegate int MyDelegate (string s));

delegate <return type> <delegate-name> <parameter list>

224 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Instantiating Delegates

Delegates new keyword


method Delegates
parameter parameter

public delegate void printString(string s);


printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

program delegate return type


interger type parameter interger
delegate method

using System;

delegate int NumberChanger(int n);


namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);

225 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("Value of Num: {0}", getNum());


Console.ReadKey();
}
}
}

alue of Num: 35
Value of Num: 175

Multicasting of a Delegates

Delegate object object +


delegate
degelate -
Multicasting program

using System;

delegate int NumberChange(int n);


namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)


{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
NumberChange nc;

226 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

NumberChange nc1 = new NumberChange(AddNum);


NumberChange nc2 = new NumberChange(MultNum);
nc = nc1;
nc += nc2;
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

Value of Num: 75

Use of Delegates

Delegate Delegate printstring


return parameter method
method print console print
method file write

using System;
using System.IO;

namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// delegate declaration
public delegate void printString(string s);

// this method prints to the console


public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}
//this method prints to a file
public static void WriteToFile(string s)
{
fs = new FileStream("message.txt",
FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs);

227 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
public static void sendString(printString ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}

The String is: Hello World

228 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Events user mouse Click ( ) mouse wheel user


user mouse E
key C Event Event
class member Events delegate
event Delegate Delegate
Event method
static method event class name Instance
method object Event method
+= remove -=
Delegate parameter Event parameter

Declaring Events
Events Events Delegate
event keyword Events create
Keyword: event
Event event-delegate object-name
Event-delegate: delegate name
Object-name: event name

public delegate void BoilerLogHandler(string status);


//Defining event based on the above delegate
public event BoilerLogHandler BoilerEventLog;
Delegate name B event name E Event

using System;
namespace SimpleEvent
{

229 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;

public class EventTest


{
private int value;
public delegate void NumManipulationHandler();

public event NumManipulationHandler ChangeNum;

protected virtual void OnNumChanged()


{
if (ChangeNum != null)
{
ChangeNum();
}
else
{
Console.WriteLine("Event fired!");
}
}
public EventTest(int n)
{
SetValue(n);
}
public void SetValue(int n)
{
if (value != n)
{
value = n;
OnNumChanged();
}
}
}
public class MainClass
{
public static void Main()
{
EventTest e = new EventTest(5);
e.SetValue(7);
e.SetValue(11);
Console.ReadKey();
}
}
}

Event Fired!
Event Fired!
Event Fired!

230 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

program program
file Auto record system Hot water boiler system
temperature pressure auto
wraing
auto

using System;
using System.IO;

namespace BoilerEventAppl
{

// boiler class
class Boiler
{
private int temp;
private int pressure;
public Boiler(int t, int p)
{
temp = t;
pressure = p;
}

public int getTemp()


{
return temp;
}
public int getPressure()
{
return pressure;
}
}
// event publisher
class DelegateBoilerEvent
{
public delegate void BoilerLogHandler(string status);

//Defining event based on the above delegate


public event BoilerLogHandler BoilerEventLog;

public void LogProcess()


{
string remarks = "O. K";
Boiler b = new Boiler(100, 12);
int t = b.getTemp();
int p = b.getPressure();
if(t > 150 || t < 80 || p < 12 || p > 15)
{

231 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

remarks = "Need Maintenance";


}
OnBoilerEventLog("Logging Info:\n");
OnBoilerEventLog("Temparature " + t + "\nPressure: " + p);
OnBoilerEventLog("\nMessage: " + remarks);
}

protected void OnBoilerEventLog(string message)


{
if (BoilerEventLog != null)
{
BoilerEventLog(message);
}
}
}
// this class keeps a provision for writing into the log file
class BoilerInfoLogger
{
FileStream fs;
StreamWriter sw;
public BoilerInfoLogger(string filename)
{
fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
}
public void Logger(string info) {
sw.WriteLine(info);
}
public void Close()
{
sw.Close();
fs.Close();
}
}
// The event subscriber
public class RecordBoilerInfo
{
static void Logger(string info)
{
Console.WriteLine(info);
}//end of Logger

static void Main(string[] args)


{
BoilerInfoLogger filelog = new BoilerInfoLogger("e:\\boiler.txt");
DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent();
boilerEvent.BoilerEventLog += new DelegateBoilerEvent.BoilerLogHandler(Logger);
boilerEvent.BoilerEventLog += new
DelegateBoilerEvent.BoilerLogHandler(filelog.Logger);
boilerEvent.LogProcess();
Console.ReadLine();
filelog.Close();

232 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}//end of main

}//end of RecordBoilerInfo
}

Logging info:
Temperature 100
Pressure 12
Message: O. K

233 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

( ) Data
Class Collection Class Stacks Queues List
Hash Table Collection Class
Collection Class Data
Class

Various Collection Classes and Their Useage


C# Collection Class Collection Class
System.Collection Namespace
Class Description and useage
Index Data ( ) Object
Array
Array Index Iteam
ArrayList
Array size ( ) size
Data

Hashtable element Key collection
Key element ( ) value
key/value
Hashtable
Item key value
size Array List

Hashtable key
SortedList key value
Index
L - ,F - item
Item pushing Method
Stack
popping Method

234 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Stack Queue F ,F -O
Item
Queue
enqueue Method
deque Method
Binary value 0 1
BitArray Index

ArrayList
ArrayList Object Index Object
Array Index Item Add Remove
Add,Remove Array size
S Arraylist auto
ArrayList Dynamic memory allocation ,adding,searching,sorting

Methods and Properties of the ArrayList Class


Property Description
Capacity ArrayList Get ,Set

Count Element Get

IsFixedSize ArrayList Element Fix size Get

isReadOnly ReadOnly Get

Item Index Item Get,Set


ArrayList Method

S.N Method Name & Purpose


public virtual int Add (object value);
1
ArrayList Object
Public virtual void AddRange (Icollection c);
2 ArrayList Item ( ) Icollection element

Public virtaul void Clear ();
3
ArrayList element
Public virtual bool Contains (objcet item);
4 ArrayList item return
type
Public virtual ArrayList GetRange (int index,int count);
5
index count ArrayList ArrayList

235 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Source ArrayList

Public virtual int IndexOf (object);


6 object index object
-1
public virtual void Insert( int index, object value );
7 ArrayList x

public virtual void InsertRange( int index, ICollection c );
8
x icollection
public virtual void Remove( object obj );
9 object object
object
public virtual void RemoveAt( int index );
10
object index
public virtual void RemoveRange( int index, int count );
11 Index count object

public virtual void Reverse();
12 ArrayList element

public virtual void SetRange( int index, ICollection c );
13 Icollection element ArrayList copy index

public virtual void Sort();
14
ArrayList element
public virtual void TrimToSize();
15 ArrayList element ArrayList x

ArrayList

using System;
using System.Collections;
namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{

236 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

ArrayList al = new ArrayList();


Console.WriteLine("Adding some numbers:");
al.Add(45);
al.Add(78);
al.Add(33);
al.Add(56);
al.Add(12);
al.Add(23);
al.Add(9);
Console.WriteLine("Capacity: {0} ", al.Capacity);
Console.WriteLine("Count: {0}", al.Count);
Console.Write("Content: ");
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.Write("Sorted Content: ");
al.Sort();
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}

Adding some numbers:


Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Content: 9 12 23 33 45 56 78

Hashtable

Hashtable Hashtable element collection


key value key value
value key
- -
Hashtable Method Properties

237 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Methods and Properties of the Hashtable Class


Property Description
Count Hashtable key,value Get
Hashtable Element Fix size Get
IsFixedSize

isReadOnly Hashtable ReadOnly Get

Item key Hashtable value Get,Set

Keys Hashtable Keys Icollection Get

Values Hashtable Values Icollection Get

Hashtable Class method


S.N Method Name & Purpose
Public virtual void Add (Object key,Object value);
1 key value element Hashtable

public virtual void Clear();
2
Hashtable element
public virtual bool ContainsKey( object key );
3 key Hashtable /
B
public virtual bool ContainsValue( object value );
4 value Hashtable /
B
public virtual void Remove( object key );
5
value

using System;
using System.Collections;

namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1, "U Bu");
ht.Add(2, "Mg Hla Win");
ht.Add(3, "Daw Aye Aye");
ht.Add(4, "U Ko Ko Kyi");

238 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

ht.Add(5, "Daw Hla Hla");


ht.Add(6, "Mg Mya Hlaing");
ht.Add(7, "U Aung Aung");

if (ht.ContainsValue("Daw Phyu Phyu"))


{
Console.WriteLine("This name is already in the list");
}
else
{
ht.Add(8, "Daw Phyu Phyu");
}
// Get a collection of the keys
ICollection key = ht.Keys;
foreach (int k in key)
{
Console.WriteLine(k.ToString() + ": " + ht[k]);
} Console.ReadKey();
}
}
}

8: Daw Phyu Phyu


7: U Aung Aung
6: Ma Mya Hlaing
5: Daw Hla Hla
4: U Ko Ko Kyi
3: Daw Aye Aye
2: Mg Hla Win
1: U Ba

SortedList

SortedList Hashtable Element collection Hashtable


key,value Hashtable
SortedList Element key
SortedList Method
Properties
Methods and Properties of the SortedList Class

Property Description
SortedList / Get,Set
Capacity

239 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Count SortedList , Get


SortedList Element Fix size Get
IsFixedSize

isReadOnly SortedList ReadOnly Get

Item key SortedList value Get,Set

Key SortedList Keys Icollection Get

Values SortedList value Icollection Get

SortedList Class method

S.N Method Name & Purpose


public virtual void Add( object key, object value );
1 key,value element SortedList

public virtual void Clear();
2
SortedList element
public virtual bool ContainsKey( object key );
3
SortedList key /
public virtual bool ContainsValue( object value );
4
SortedList value /
public virtual object GetByIndex( int index );
5
Index value
public virtual object GetKey( int index );
6
Index key
public virtual IList GetKeyList();
7
SortedList key List
public virtual IList GetValueList();
8
SortedList value List
public virtual int IndexOfKey( object key );
9
key SortedList Index
public virtual int IndexOfValue( object value );
10
value SortedList Index
public virtual void Remove( object key );
11
key key element SortedList
public virtual void RemoveAt( int index );
12
index element SortedList
public virtual void TrimToSize();
13
SortedList element SortedList fix size

240 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
SortedList sl = new SortedList();
sl.Add("1", "U Ba");
sl.Add("2", "Mg Hla Win");
sl.Add("3", "Daw Aye Aye");
sl.Add("4", "U Ko Ko Kyi");
sl.Add("5", "Daw Hla Hla");
sl.Add("6", "Ma Mya Hlaing");
sl.Add("7", "U Aung Aung");

if (sl.ContainsValue("Daw Phyu Phyu"))


{
Console.WriteLine("This name is already in the list");
}
else
{
sl.Add("8", "Daw Phyu Phyu");
}

// get a collection of the keys.


ICollection key = sl.Keys; foreach (string k in key)
{
Console.WriteLine(k + ": " + sl[k]);
}
Console.ReadKey();
}
}
}

1: U Ba
2: Mg Hla Win
3: Daw Aye Aye
4: U Ko Ko Kyi
5: Daw Hla Hla
6: Ma Mya Hlaing
7: U Aung Aung
8: Daw Phyu Phyu

241 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Stack

Stack Last-in,First-out collection A A String


Item M
Stack A A M
M ,A A Stack
L - ,F - Stack Method Properties

Methods and Properties of the Stack Class


Property Description
Count Stack element Get

Stack Method
S.N Method Name & Purpose
public virtual void Clear();
1
Stack element
public virtual bool Contains( object obj );
2 object Stack /

public virtual object Peek();
3 Stack ( ) object

public virtual object Pop();
4 Stack ( ) object

public virtual object Push();
5
Stack object
public virtual object[] ToArray();
6
Stack object Array
Stack

using System;
using System.Collections;

namespace CollectionsApplication
{
class Program

242 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
static void Main(string[] args)
{
Stack st = new Stack();
st.Push("Min");
st.Push("Ko");
st.Push("Aung");
st.Push("Mg");
Console.WriteLine("Current stack: ");
foreach (string str in st)
{
Console.Write(str + " ");
}

Console.WriteLine();
st.Push(".");
st.Push("Dr");
Console.WriteLine("The next popable value in stack: {0}", st.Peek());
Console.WriteLine("Current stack: ");
foreach (string str in st)
{
Console.Write(str + " ");
}
Console.WriteLine();
Console.WriteLine("Removing values ");
st.Pop();
st.Pop();
st.Pop();
Console.WriteLine("Current stack: ");
foreach (string str in st)
{
Console.Write(str + " ");
}
Console.ReadKey();
}
}
}

Current stack:
Mg Aung Ko Min
The next popable value in stack: Dr
Current stack:
Dr.Mg Aung Ko Min
Removing values
Current stack:
Aung Ko Min

243 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Queue

Queue Stack Queue First-in,First-out collection


Stack L - ,F - Queue
object Queue
object enqueue method
dequeue method Queue Method Properties

Methods and Properties of the Queue Class


Property Description
Count Queue element Get

Queue Method
S.N Method Name & Purpose
public virtual void Clear();
1
Queue element
public virtual bool Contains( object obj );
2
object Queue /
public virtual object Dequeue();
3 Queue ( ) object

public virtual object Enqueue();
4
Queue object
public virtual object[] ToArray();
5
Queue object Array
public virtual void TrimToSize();
6 Queue element Queue Fx S

Queue

using System;
using System.Collections;
namespace Collection_Queue {
class Program {
static void Main(string[] args)
{
Queue q = new Queue();
q.Enqueue("Dr");

244 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

q.Enqueue(".");
q.Enqueue("Aung");
q.Enqueue("Ko");
Console.WriteLine("Current queue: ");

foreach (string str in q)


Console.Write(str + " ");

Console.WriteLine();
q.Enqueue("Min");
q.Enqueue("Thu");

Console.WriteLine("Current queue: ");


foreach (string str in q)
Console.Write(str + " ");
Console.WriteLine();
Console.WriteLine("Removing some values ");
string stri = q.Dequeue().ToString();
Console.WriteLine("The removed value: {0}", stri);
stri = q.Dequeue().ToString();
Console.WriteLine("The removed value: {0}", stri);
Console.ReadKey();
}
}
}

Current queue:
Dr.Aung Ko
Current queue:
Dr.Aung Ko Min Thu
Removing some values
The removed value:Dr
The removed value:.

BitArray

0 1 bit Array BitArray Class C Sharp


BitArray bit 0 ,1
1 True
0 false

Methods and Properties of the BitArray Class

Property Description
Count BitArray bit Get

245 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

IsReadOnly BitArray ReadOnly


BitArray position Item Get,Set
Item

Length BitArray G ,S

BitArray Class Method


S.N Method Name & Purpose
public BitArray And( BitArray value );
BitArray A O A Ture
1
False False False False False True
True
public bool Get( int index );
2
BitArray postion Item Get
public BitArray Not();
3 BitArray Bit value (invert) Item 0
1 1 0
public BitArray Or( BitArray value );
BitArray Or Operation O Ture
4
F True False F False True
True
public void Set( int index, bool value );
5 index item (True Or False) (Set)

public void SetAll( bool value );
6 BitArray item (True Or False) (Set)

public BitArray Xor( BitArray value );
7
BitArray Ex O O

BitArray

using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)

246 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
//creating two bit arrays of size 8
BitArray ba1 = new BitArray(8);
BitArray ba2 = new BitArray(8);
byte[] a = { 60 };
byte[] b = { 13 };
//storing the values 60, and 13 into the bit arrays
ba1 = new BitArray(a);
ba2 = new BitArray(b);
//content of ba1
Console.WriteLine("Bit array ba1: 60");
for (int i = 0; i < ba1.Count; i++)
{
Console.Write("{0, -6} ", ba1[i]);
}
Console.WriteLine();
//content of ba2
Console.WriteLine("Bit array ba2: 13");
for (int i = 0; i < ba2.Count; i++)
{
Console.Write("{0, -6} ", ba2[i]);
}
Console.WriteLine();
BitArray ba3 = new BitArray(8);
ba3 = ba1.And(ba2);
//content of ba3
Console.WriteLine("Bit array ba3 after AND operation: 12");
for (int i = 0; i < ba3.Count; i++)
{
Console.Write("{0, -6} ", ba3[i]);
}
Console.WriteLine();
ba3 = ba1.Or(ba2);
//content of ba3
Console.WriteLine("Bit array ba3 after OR operation: 61");
for (int i = 0; i < ba3.Count; i++)
{
Console.Write("{0, -6} ", ba3[i]);
}
Console.WriteLine();
Console.ReadKey();
}
}
}

Bit array ba1: 60


False False True True True True False False
Bit array ba2: 13
True False True True False False False False
Bit array ba3 after AND operation: 12

247 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

False False True True False False False False


Bit array ba3 after OR operation: 61
True False True True False False False False

248 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Anonymous methods Delegate


Delegate same signature (parameter )
Delegate ()
Anonymous method Delegate parameter code
block Anonymous N C
= x) { C . L "A M : {0}", x);}; Anonymous method
method name method body return type
Anonymous method method name method body

Syntax for Writing an Anonymous Method

Anonymous method Delegate


delegate keyword Anonymous method
Anonymous

delegate void NumberChanger(int n);


...
NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); };

syntax code block Console.WriteLine("Anonymous


Method: {0}", x); Anonymous method method body

using System;

delegate void NumberChanger(int n);


namespace DelegateAppl
{
class TestDelegate

249 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
static int num = 10;
public static void AddNum(int p)
{
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void MultNum(int q)
{
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances using anonymous method
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
nc(10);
//instantiating the delegate using the named methods
nc = new NumberChanger(AddNum);
//calling the delegate using the named methods
nc(5);
//instantiating the delegate using another named methods
nc = new NumberChanger(MultNum);
//calling the delegate using the named methods
nc(2);
Console.ReadKey();
}
}
}

Anonymous Method: 10
Named Method: 15
Named Method: 30

250 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C# variable Unsafe pointer type Unsafe


code ( ) unmanaged code pointer variable Unsafe class
Struct member field S { } ) Unsafe
programmer
dll file function
Memory address pointer
unsafe codes program unsafe command line
compiler
csc /unsafe prog1.cs

Visual Studio IDE Solution Explorer project C


properties box Build tab click Allow unsafe code
check

Pointer Variables

Pointer variable variable value


variable memory address
Reference type Reference type
Pointer variable address
Pointer Pointer variable
variable data type ( int var=30; int *
p=& var)
No Operator Meaning
1 & address-of operator variable address pointer

2 * D pointer address variable

3 -> P (x->y)

251 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Pointer

type *var-name;
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace @unsafe
{
class Program
{
static unsafe void Main(string[] args)
{
int var = 20;
int* p = &var;
Console.WriteLine("Data is: {0} ", var);
Console.WriteLine("Address is: {0}", (int)p);
Console.ReadKey();
}
}
}

Data is: 20
Address is: 99215364

Retrieving the Data Value Using a Pointer

pointer variable data value ToString method


data output

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

252 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

namespace eunsafe
{
class Program
{
public static void Main()
{
unsafe
{
int var = 20;
int* p = &var;
Console.WriteLine("Data is: {0} " , var);
Console.WriteLine("Data is: {0} " , p->ToString());
Console.WriteLine("Address is: {0} " , (int)p);
}
Console.ReadKey();
}
}
}

Data is: 20
Data is: 20
Address is: 77128984

Passing Pointers as Parameters to Methods

Funtion pointer parameters passing


program

using System;
namespace UnsafeCodeApplication
{
class TestPointer
{
public unsafe void swap(int* p, int* q)
{
int temp = *p;
*p = *q;
*q = temp;
}
public unsafe static void Main()
{
TestPointer p = new TestPointer();

253 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

int var1 = 10;


int var2 = 20;
int* x = &var1;
int* y = &var2;
Console.WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2);
p.swap(x, y);
Console.WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2);
Console.ReadKey();
}
}
}

Before Swap: var1: 10, var2: 20


After Swap: var1: 20, var2: 10

Accessing Array Elements Using a Pointer

array data pointer output


array int array pointer
type variable type ( int *p int [] p
) Pointer variable increment pointer variable
Fx Array x
pointer array data pointer variable fixed
keyword x program

using System;
namespace UnsafeCodeApplication1
{
class TestPointer
{
public unsafe static void Main()
{
int[] list = { 10, 100, 200 };
fixed (int* ptr = list)
/* let us have array address in pointer */
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Address of list[{0}]={1}", i, (int)(ptr + i));
Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i));
}
Console.ReadKey();

254 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
}
}

Address of list[0] = 31627168


Value of list[0] = 10
Address of list[1] = 31627172
Value of list[1] = 100
Address of list[2] = 31627176
Value of list[2] = 200

255 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Thread Thread
process Process program
execution Process Process program
statements line code step by step ( ) Line code

thread Process
thread Process
thread Thread program execution
program single thread single process
executed program (Time)
Process Time
thread
( thread
thread
)

Thread Life Cycle

Thread life Cycle thread life Thread life cycle


system.threading object thread life
Thread create execute
thread Thread Life cycle
states states
The Unstarted State: thread create start
method Unstarted state
The Ready State: thread run CPU Cycle

256 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

The Not Runnable State: thread run


Sleep waiting I/O operation
block
The Dead State: thread execute ( ) Aborted

The Main Thread

Process execute thread main thread Thread


System.Threading.thread class
System.Threading.thread class MultiThread application thread create
access Program execute
auto main thread create Thread class create
Thread class CurrentThread property program

using System;
using System.Threading;

namespace MultithreadingApplication
{
class MainThreadProgram
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
}

This is MainThread

257 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Commonly Used Properties and Methods of the Thread Class

Thread properties method



Properties Description
CurrentThread CurrentThread properties thread
IsAlive Thread IsAlive
properties
IsBackground Thread foreground background Thread create
default foreground thread
background thread IaBackground properties

IsThreadPoolThread Thread thread pool IsThreadPoolThread
properties
ManagedThreadId thread id ( ) name

Name Name read-write thread name read
write
Priority Thread priority ()
(Highest,AboveNormal,Normal,BelowNormal,Lowest).
Default Norma
ThreadState Thread state
thread ready state Unstart state

S.N Method Name & Description


1 public void Abort()
Abort method terminate method terminate

2 public static AppDomain GetDomain()
Current thread domain

3 public void Interrupt() Interrupts a thread that is in the WaitSleepJoin thread state.

4 public void Join()


Join method Join Thread join
thread

5 public static void ResetAbort()

258 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

thread Abort Abort ResetAbort()


method

6 public void Start()


Thread Start Start() method

7 public static void Sleep( int millisecondsTimeout ) thread


Sleep () method

Creating Thread
System Threads Class thread create thread class
start() method program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace threadf
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}

In Main: Creating the Child thread


Child thread starts

259 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Managing Thread
Threads managing threads class method
thread threads class Sleep()
method thread

using System;
using System.Collections.Generic;
using System.Threading;

namespace threadf
{
class threadsleep
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
// the thread is paused for 5000 milliseconds
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds",
sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}

In Main: Creating the Child thread


Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes

260 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Destroying Threads
Thread
thread Abort() method
exception ThreadAbortException Catch
Finally program

using System;
using System.Collections.Generic;
using System.Threading;

namespace threadf
{
class threadabort
{
public static void CallToChildThread()
{
try
{
Console.WriteLine("Child thread starts");
// do some work, like counting to 10
for (int counter = 0; counter <= 10; counter++)
{
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("Child Thread Completed");
}
catch (ThreadAbortException e)
{
Console.WriteLine("Thread Abort Exception");
}
finally
{
Console.WriteLine("Couldn't catch the Thread Exception");
}
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
//stop the main thread for some time
Thread.Sleep(2000);
//now abort the child
Console.WriteLine("In Main: Aborting the Child thread");
childThread.Abort();

261 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.ReadKey();
}
}
}

In Main: Creating the Child thread


Child thread starts
0
1
2
In Main: Aborting the Child thread
Thread Abort Exception
Couldn't catch the Thread Exception

262 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Keywords C# Language C#
Keywords Reserved Keywords Contextual Keywords Reserved Keywords
C# language name Reserved Keywords
Identifier ( . string as) Contextual Keywords Identifier
( . int add) C# Keywords
)

Abstract
Abstract keyword Class Methods Properties Indexers Events
Abstract implementation Implementation
statement ( public abstract
void Area();) Abstract keyword
Abstract keyword

Class Abstract keyword Abstract class Class
object
Abstract Class method Accessors
Abstract Class class
Sealed Class
Abstract Class non-Abstract inherit method
properties Accessor Implementation

abstract class BaseClass // Abstract class


{
protected int _x = 100;
protected int _y = 150;
public abstract void AbstractMethod(); // Abstract method
public abstract int X { get; }
public abstract int Y { get; }

263 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
class DerivedClass : BaseClass
{
public override void AbstractMethod()
{
_x++;
_y++;
}
public override int X // overriding property
{
get
{
return _x + 10;
}
}
public override int Y // overriding property
{
get
{
return _y + 10;
}
}
static void Main()
{
DerivedClass o = new DerivedClass();
o.AbstractMethod();
Console.WriteLine("x = {0}, y = {1}", o.X, o.Y);
}
}

x = 111, y = 161

As

A C K reference
conversions, nullable conversions, and boxing conversions user-defined
conversions

class ClassA { }
class ClassB { }

264 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

class MainClass
{
static void Main()
{
object[] objArray = new object[6];
objArray[0] = new ClassA();
objArray[1] = new ClassB();
objArray[2] = "hello";
objArray[3] = 123;
objArray[4] = 123.4;
objArray[5] = null;
for (int i = 0; i < objArray.Length; ++i)
{
string s = objArray[i] as string;
Console.Write("{0}:", i);
if (s != null)
{
Console.WriteLine("'" + s + "'");
}
else
{
Console.WriteLine("not a string");
}
}
}
}

0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string

Base

B C D Base keyword
)

B C D C
)O
D

265 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

B C
M S B K

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace boolcheck
{
public class BaseClass
{
int num;
public BaseClass()
{
Console.WriteLine("in BaseClass()");
}
public BaseClass(int i)
{
num = i;
Console.WriteLine("in BaseClass(int i)");
}
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}");
Console.WriteLine("SSN: {0}");
}
}
public class DerivedClass : BaseClass
{
// This constructor will call BaseClass.BaseClass()
public DerivedClass()
: base()
{
}
// This constructor will call BaseClass.BaseClass(int i)
public DerivedClass(int i)
: base(i)
{
}
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Driveclass");
}
static void Main()
{
DerivedClass md = new DerivedClass();

266 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

DerivedClass md1 = new DerivedClass(1);


md.GetInfo();
Console.ReadKey();
}
}
}

in BaseClass()
in BaseClass(int i)
Name: {0}
SSN: {0}
Driveclass

Bool

B .B
B K

using System;
using System.Text;

namespace boolcheck
{
public class BoolKeyTest
{
static void Main()
{
Console.Write("Enter a character: ");
char c = (char)Console.Read();
if (Char.IsLetter(c))
{
Console.WriteLine("The character is not uppercase..");
}
else
{
Console.WriteLine("The character is uppercase..");
}
Console.ReadKey();
}
}
}

267 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Enter a character: c
The character is not uppercase.

Break

B )

using System;
using System.Text;

namespace breaktest
{

class BreakTest
{
static void Main()
{
for (int i = 1; i <= 100; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}

1
2
3
4

Byte

268 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Byte keyword integral type Byte keyword



Type Range Size .NET Framework type


byte 0 to 255 Unsigned 8-bit integer System. Byte

Byte keyword
byte myByte = 255;

C B short, ushort, int, uint, long, ulong, float, double, or decimal


implicit conversio D
numeric types B
Ex

byte x = 10, y = 20;


byte z = x + y; error
// OK: explicit conversion:
byte z = (byte)(x + y);

Case
Case keyword switch statement Switch Statement Control
Switch case labels

int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}

Catch
Catch keyword Try-catch statement Try statement Catch

269 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

try block statements Error


catch block Exception catch
block Error (Handle) catch block

class TryFinallyTest
{
static void ProcessString(string s)
{
if (s == null)
{
throw new ArgumentNullException();
}
}
static void Main()
{
string s = null; // For demonstration purposes.
try
{
ProcessString(s);
}

catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}

System.ArgumentNullException: Value cannot be null.


at TryFinallyTest.Main() Exception caught.

Char
Char keyword System.Char Unicode
character char keyword properties
Type Range Size .NET Framework type
char U+0000 to U+ffff Unicode 16-bit character System. Char
Char variable character literals, hexadecimal escape sequence, or Unicode

270 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

char[] chars = new char[4];

chars[0] = 'X'; // Character literal


chars[1] = '\x0058'; // Hexadecimal
chars[2] = (char)88; // Cast from integral type
chars[3] = '\u0058'; // Unicode

foreach (char c in chars)


{
Console.Write(c + " ");
}

X X X X

Checked

Intergral-type conversions
D ) /
Checked keyword Expression constant values
expression Compiler error(outside the range) D
Expression non-constant values
Checked keyword

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace checkedeg
{
class OverFlowTest
{
// Set maxIntValue to the maximum value for integers.
static int maxIntValue = 2147483647;
// Using a checked expression.
static int CheckedMethod()
{
int z = 0;
try

271 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
// The following line raises an exception because it is checked.
z = checked(maxIntValue + 10);
}
catch (System.OverflowException e)
{
// The following line displays information about the error.
Console.WriteLine("CHECKED and CAUGHT: " + e.ToString());
}
// The value of z is still 0.
return z;
}
// Using an unchecked expression.
static int UncheckedMethod()
{
int z = 0;
try
{
// The following calculation is unchecked and will not
// raise an exception.
z = maxIntValue + 10;
}
catch (System.OverflowException e)
{
// The following line will not be executed.
Console.WriteLine("UNCHECKED and CAUGHT: " + e.ToString());
}
// Because of the undetected overflow, the sum of 2147483647 + 10 is
// returned as -2147483639.
return z;
}
static void Main()
{
Console.WriteLine("\nCHECKED output value is: {0}",
CheckedMethod());
Console.WriteLine("UNCHECKED output value is: {0}",
UncheckedMethod());
int ten = 10;
int i2 = 2147483647 + ten;
Console.WriteLine(i2);
//Console.WriteLine(checked(2147483647 + ten)); compiler
Console.ReadKey();
}
}
}

CHECKED and CAUGHT: System.OverflowException: Arithmetic operation resulted in


an overflow.
at checkedeg.OverFlowTest.CheckedMethod() in c:\Users\Yanku-Pc\Documents\Visu

272 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

al Studio 2012\Projects\checkedeg\checkedeg\Program.cs:line 21

CHECKED output value is: 0


UNCHECKED output value is: -2147483639
-2147483639

Class
Class class keyword
class TestClass
{
// Methods, properties, fields, events, delegates
// and nested classes go here.
}
C C
I
Inheritance Example
None class ClassA { }
Single class DerivedClass: BaseClass { }
None, implements two interfaces class ImplClass: IFace1, IFace2 { }
Single, implements one interface class ImplDerivedClass: BaseClass, IFace1 { }

Class Constructors, Destructors, Constants, Fields, Methods, Properties, Indexers,


Operators, Events, Delegates, Classes, Interfaces Structs

class Child
{
private int age;
private string name;

// Default constructor:
public Child()
{
name = "N/A";
}

// Constructor:
public Child(string name, int age)
{
this.name = name;
this.age = age;
}
// Printing method:
public void PrintChild()
{
Console.WriteLine("{0}, {1} years old.", name, age);
}

273 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
class StringTest
{
static void Main()
{
// Create objects by using the new operator:
Child child1 = new Child("Craig", 11);
Child child2 = new Child("Sally", 10);
// Create an object using the default constructor:
Child child3 = new Child();
// Display results:
Console.Write("Child #1: ");
child1.PrintChild();
Console.Write("Child #2: ");
child2.PrintChild();
Console.Write("Child #3: ");
child3.PrintChild();
}
}

Child #1: Craig, 11 years old.


Child #2: Sally, 10 years old.
Child #3: N/A, 0 years old.

Const

C L C K
C
C initialized
initialized C -
-

public class ConstTest


{
class SampleClass
{
public int x;
public int y;
public const int c1 = 5;
public const int c2 = c1 + 5;

public SampleClass(int p1, int p2)


{
x = p1;
y = p2;
}
}

274 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

static void Main()


{
SampleClass mC = new SampleClass(11, 22);
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
Console.WriteLine("c1 = {0}, c2 = {1}",
SampleClass.c1, SampleClass.c2 );
}
}

x = 11, y = 22
c1 = 5, c2 = 10
Continue

C S

class ContinueTest
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
if (i < 9)
{
continue;
}
Console.WriteLine(i);
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}

9
10

Decimal

Decimal keyword 12 - Decimal type precision


financial monetary calculations Decimal

275 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Decimal keyword precision Approximate


Range
Type Approximate Range Precision .NET Framework type
decimal (-7.9 x 1028 to 7.9 x 1028) / (100 to 28) 28-29 significant digits System. Decimal

Decimal numeric real literal M



decimal myMoney = 300.5m;

Integral types decimal implicitly convertion


Implicit Type Convertion smaller intergral type larger intergral type
Child Class Parent Class Explicit Type Convertion C#
pre-defined Functions( .C . S ) )
Explicit Type Convertion

decimal myMoney = 300;


decimal myMoney = 99.9m;
double x = (double)myMoney;// Explict type Cast Operator
myMoney = (decimal)x;

public class TestDecimalFormat


{
static void Main()
{
decimal x = 0.999m;
decimal y = 9999999999999999999999999999m;
decimal d = 9.1m;
int y = 3;
Console.WriteLine(d + y); // Result converted to decimal
Console.WriteLine("My amount = {0:C}", x);
Console.WriteLine("Your amount = {0:C}", y);
}
}

12.1
My amount = $1.00
Your amount = $9,999,999,999,999,999,999,999,999,999.00

276 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Default

Switch D
G
( T temp = default(T);)

Delegate
Delegate type method Encapsulate
anonymous method Delegate Delegate Events
Events Delegate
value parameter
public delegate void TestDelegate(string message);
public delegate int TestDelegate(MyType m, long num);

// Declare delegate -- defines required signature:


delegate double MathAction(double num);

class DelegateTest
{
// Regular method that matches signature:
static double Double(double input)
{
return input * 2;
}

static void Main()


{
// Instantiate delegate with named method:
MathAction ma = Double;

// Invoke delegate ma:


double multByTwo = ma(4.5);
Console.WriteLine("multByTwo: {0}", multByTwo);

// Instantiate delegate with anonymous method:


MathAction ma2 = delegate(double input)
{
return input * input;
};
double square = ma2(5);
Console.WriteLine("square: {0}", square);
// Instantiate delegate with lambda expression
MathAction ma3 = s => s * s * s;
double cube = ma3(4.375);
Console.WriteLine("cube: {0}", cube);

277 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

multByTwo: 9
square: 25
cube: 83.740234375

Do
Do statement Condition block statement(s)
C block

public class TestDoWhile


{
public static void Main ()
{
int x = 0;
do
{
Console.WriteLine(x);
x++;
} while (x < 5);
}
}

0
1
2
3
4

Double

Double keyword floating-point value 64-bit


Double keyword precision Approximate Range

278 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Type Approximate range Precision .NET Framework type


double 5.0 10324 to 1.7 10308 15-16 digits System. Double

Numeric real literal assignment(=) operator double value


Double integer type D

double x = 3D

class MixedTypes
{
static void Main()
{
int x = 3;
float y = 4.5f;
short z = 5;
double w = 1.7E+3;
// Result of the 2nd argument is a double:
Console.WriteLine("The sum is {0}", x + y + z + w);
}
}

The sum is 1712.5

Else

E I B
x B
B

bool result = true;

if (result)
{
Console.WriteLine("The variable is set to true.");
}
else
{
Console.WriteLine("The variable is set to false.");
}

279 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Enum
Enum keyword enumeration
name constants enumeration list Enumeration list symbol
Symbol , symbole
index value ( Array index )Default 0
1,2,3 Auto
Enum
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

Enum D Sun Mon Tue Web Thu Fri Sat


Symbol () Symbol Sum Index Value 0 Mon 1 Tue
2 Enum Symbol
symbol index Value ( ) Id
Index Value

public class EnumTest


{
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

static void Main()


{
int x = (int)Days.Sun;
int y = (int)Days.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}

Sun = 0
Fri = 5

Event
Events user mouse Click ( ) mouse wheel user
user mouse E
key C Event Event
class member Eevnt Keyword event

280 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Event Event

public class SampleEventArgs


{
public SampleEventArgs(string s) { Text = s; }
public String Text {get; private set;} // readonly
}
public class Publisher
{
// Declare the delegate (if using non-generic pattern).
public delegate void SampleEventHandler(object sender, SampleEventArgs e);

// Declare the event.


public event SampleEventHandler SampleEvent;

// Wrap the event in a protected virtual method


// to enable derived classes to raise the event.
protected virtual void RaiseSampleEvent()
{
// Raise the event by using the () operator.
if (SampleEvent != null)
SampleEvent(this, new SampleEventArgs("Hello"));
}
}

Event access modifiers Access modifiers public,


pirvate,protected,internal protected internal keyword event
keyword

Keyword Description For more information


static Event static keyword Static Classes and Static
Class Members (C#
Programming Guide)
Event
virtual Derived class override keyword Event Inheritance (C#
Programming Guide)

sealed Sealed keyword derived class



abstract Abstract keyword compiler event
event
derived class implement

281 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

.Explicit
Explicit Type Convertion C# pre-defined
Functions( .C . S ) )
Explicit Type Convertion
Explicit Conversion operator Conversion operator
Ex

// Must be defined inside a class called Fahrenheit:


public static explicit operator Celsius(Fahrenheit fahr)
{
return new Celsius((5.0f / 9.0f) * (fahr.degrees - 32));
}

class Celsius
{
public Celsius(float temp)
{
degrees = temp;
}
public static explicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
}
public float Degrees
{
get { return degrees; }
}
private float degrees;
}

class Fahrenheit
{
public Fahrenheit(float temp)
{
degrees = temp;
}
// Must be defined inside a class called Fahrenheit:
public static explicit operator Celsius(Fahrenheit fahr)
{
return new Celsius((5.0f / 9.0f) * (fahr.degrees - 32));
}
public float Degrees
{
get { return degrees; }
}
private float degrees;
}

class MainClass
{
static void Main()
{

282 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Fahrenheit fahr = new Fahrenheit(100.0f);


Console.Write("{0} Fahrenheit", fahr.Degrees);
Celsius c = (Celsius)fahr;

Console.Write(" = {0} Celsius", c.Degrees);


Fahrenheit fahr2 = (Fahrenheit)c;
Console.WriteLine(" = {0} Fahrenheit", fahr2.Degrees);
}
}

100 Fahrenheit = 37.77778 Celsius = 100 Fahrenheit

Extren
Extren keyword external assembly external
assembly Method implement extern
modifier extern modifier D I
Extern method method static

[DllImport("avifil32.dll")]
private static extern void AVIFileInit();

//using System.Runtime.InteropServices;
class ExternTest
{
[DllImport("User32.dll", CharSet=CharSet.Unicode)]
public static extern int MessageBox(IntPtr h, string m, string c, int type);

static int Main()


{
string myString;
Console.Write("Enter your message: ");
myString = Console.ReadLine();
return MessageBox((IntPtr)0, myString, "My Message Box", 0);
}

False

F )

283 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

false Operator a != b)
false Literal bool a = false;)

Finally
Finally keyword try block Exception Handle
Error
finally block finally block statements
Exception Handling

public class ThrowTestA


{
static void Main()
{
int i = 123;
string s = "Some string";
object obj = s;

try
{
// Invalid conversion; obj contains a string, not a numeric type.
i = (int)obj;

// The following statement is not run.


Console.WriteLine("WriteLine at the end of the try block.");
}
finally
{
// To run the program in Visual Studio, type CTRL+F5. Then
// click Cancel in the error dialog.
Console.WriteLine("\nExecution of the finally block after an unhandled\n" +
"error depends on how the exception unwind operation is triggered.");
Console.WriteLine("i = {0}", i);

}
}

Execution of the finally block after an unhandled


error depends on how the exception unwind operation is triggered.
i = 123

Fixed
Fixed keyword garbage collector variable
Fiexed keyword unsafe code Buffers size x
Fiexed keyword

284 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

class Point
{
public int x, y;
}
class FixedTest2
{
// Unsafe method: takes a pointer to an int.
unsafe static void SquarePtrParam (int* p)
{
*p *= *p;
}
unsafe static void Main()
{
Point pt = new Point();
pt.x = 5;
pt.y = 6;
// Pin pt in place:
fixed (int* p = &pt.x)
{
SquarePtrParam (p);
}
// pt now unpinned.
Console.WriteLine ("{0} {1}", pt.x, pt.y);
}
}

25 6

Float
Double keyword floating-point value 32-bit
Double keyword precision Approximate Range

Type Approximate range Precision .NET Framework type


float -3.4 1038to +3.4 1038 7 digits System. Single

Numeric real literal assignment(=) operator double value


Initialize Float variable F

float x = 3.5F;

285 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

class FloatTest
{
static void Main()
{
int x = 3;
float y = 4.5f;
short z = 5;
var result = x * y / z;
Console.WriteLine("The result is {0}", result);
Type type = result.GetType();
Console.WriteLine("result is of type {0}", type.ToString());
}
}

The result is 2.7


result is of type System.Single //'float' is alias for 'Single'

For
Statement ( ) block statements false
for loop Arrays data
For loop
for (initializer; condition; iterator)
{ body
}

class ForLoopTest
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}

1
2
3

286 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

4
5

Foreach
Foreach statement Array element ( ) collection object
Foreach statement collection information
collection information add ( ) remove
collection information add ( ) remove for loop

class ForEachTest
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}

0
1
1
2
3
5
8

Goto
Goto statement Label statement
Goto Statement switch-case label ( ) default label

class SwitchTest
{
static void Main()
{
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);

287 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

int cost = 0;
switch (n)
{
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
case 3:
cost += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection.");
break;
}
if (cost != 0)
{
Console.WriteLine("Please insert {0} cents.", cost);
}
Console.WriteLine("Thank you for your business.");

// Keep the console open in debug mode.


Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}

Coffee sizes: 1=Small 2=Medium 3=Large


Please enter your selection: 2
Please insert 50 cents.
Thank you for your business.

If
If statement Boolean value execute Boolean
variable result if block statement

bool result = true;

if (result)
{
Console.WriteLine("The variable is set to true.");
}
else
{
Console.WriteLine("The variable is set to false.");
}

288 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Implicit
I

I

class Digit
{
public Digit(double d) { val = d; }
public double val;
// ...other members

// User-defined conversion from Digit to double


public static implicit operator double(Digit d)
{
return d.val;
}
// User-defined conversion from double to Digit
public static implicit operator Digit(double d)
{
return new Digit(d);
}
}
class Program
{
static void Main(string[] args)
{
Digit dig = new Digit(7);
//This call invokes the implicit "double" operator
double num = dig;
//This call invokes the implicit "Digit" operator
Digit dig2 = 12;
Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);
Console.ReadLine();
}
}
}

In
In keyword foreach statement Foreach statement Array
element ( ) collection object Foreach
statement collection information
collection information add ( ) remove collection
information add ( ) remove for loop

class ForEachTest

289 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}

0
1
1
2
3
5
8
13
In(generic modifier)
In keyword generic type parameter In
keyword generic interfaces delegates
// Contravariant interface.
interface IContravariant<in A> { }

// Extending contravariant interface.


interface IExtContravariant<in A> : IContravariant<A> { }

// Implementing contravariant interface.


class Sample<A> : IContravariant<A> { }

class Program
{
static void Test()
{
IContravariant<Object> iobj = new Sample<Object>();
IContravariant<String> istr = new Sample<String>();

// You can assign iobj to istr because


// the IContravariant interface is contravariant.
istr = iobj;
}
}

Int
Int keyword integral type
range

290 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Type Range Size .NET Framework type


int -2,147,483,648 to 2,147,483,647 Signed 32-bit integer System. Int32

Int
int i = 123;

Int

// '123' is an int, so an implicit conversion takes place here:
float f = 123;

long aLong = 22;


int i1 = aLong; // Error: no implicit conversion from long.
int i2 = (int)aLong; // OK: explicit conversion.

Interface
Interface methods properties events indexers Interface class
( ) struct interface members implement Interface class
multiple inherit

interface IPoint
{
// Property signatures:
int x
{
get;
set;
}

int y
{
get;
set;
}
}
class Point : IPoint
{
// Fields:
private int _x;
private int _y;

// Constructor:
public Point(int x, int y)
{

291 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

_x = x;
_y = y;
}
// Property implementation:
public int x
{
get
{
return _x;
}

set
{
_x = value;
}
}
public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}
class MainClass
{
static void PrintPoint(IPoint p)
{
Console.WriteLine("x={0}, y={1}", p.x, p.y);
}
static void Main()
{
Point p = new Point(2, 3);
Console.Write("My Point: ");
PrintPoint(p);
}
}

My Point:

Internal
Internal keyword access modifier S internal type

public class BaseClass
{
// Only accessible within the same assembly

292 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

internal static int x = 0;


}
program Assembly1.cs Assembly1_a.cs file file
File access modifier name B
Baseclass file object
Assembly name

// Assembly1.cs
// Compile with: /target:library
internal class BaseClass
{
public static int intM = 0;
}
// Assembly1_a.cs
// Compile with: /reference:Assembly1.dll
class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // CS0122
}
}

Is
object type class
is keyword is operator overloading

class Class1 {}
class Class2 {}
class Class3 : Class2 { }

class IsTest
{
static void Test(object o)
{
Class1 a;
Class2 b;

if (o is Class1)
{
Console.WriteLine("o is Class1");
a = (Class1)o;
// Do something with "a."

293 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
else if (o is Class2)
{
Console.WriteLine("o is Class2");
b = (Class2)o;
// Do something with "b."
}

else
{
Console.WriteLine("o is neither Class1 nor Class2.");
}
}
static void Main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Class3 c3 = new Class3();
Test(c1);
Test(c2);
Test(c3);
Test("a string");
}
}

o is Class1
o is Class2
o is Class2
o is neither Class1 nor Class2.

Lock

The lock keyword marks a statement block as a critical section by obtaining the mutual-
exclusion lock for a given object, executing a statement, and then releasing the lock. The
following example includes a lock statement.

class Account
{
decimal balance;
private Object thisLock = new Object();

public void Withdraw(decimal amount)


{

294 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

lock (thisLock)
{
if (amount > balance)
{
throw new Exception("Insufficient funds");
}
balance -= amount;
}
}
}

Remarks

The lock keyword ensures that one thread does not enter a critical section of code while
another thread is in the critical section. If another thread tries to enter a locked code, it will
wait, block, until the object is released.

The section Threading (C# and Visual Basic) discusses threading.

The lock keyword calls Enter at the start of the block and Exit at the end of the block. A
ThreadInterruptedException is thrown if Interrupt interrupts a thread that is waiting to enter a
lock statement.

In general, avoid locking on a public type, or instances beyond your code's control. The
common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this
guideline:

lock (this) is a problem if the instance can be accessed publicly.


lock (typeof (MyType)) is a problem if MyType is publicly accessible.
lock("myLock") is a problem because any other code in the process using the same
string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to
protect data common to all instances.

You can't use the await keyword in the body of a lock statement.

Example

The following sample shows a simple use of threads without locking in C#.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard

295 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

//using System.Threading;

class ThreadTest
{
public void RunMe()
{
Console.WriteLine("RunMe called");
}

static void Main()


{
ThreadTest b = new ThreadTest();
Thread t = new Thread(b.RunMe);
t.Start();
}
}
// Output: RunMe called

The following sample uses threads and lock. As long as the lock statement is present, the
statement block is a critical section and balance will never become a negative number.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard

Long

L

Type Range Size .NET Framework
type
Long 9,223,372,036,854,775,808 to Signed 64-bit System. Int64
9,223,372,036,854,775,807 integer

Long
long long1 = 4294967296;

L L L
)

long long2 = 4294967296L;

296 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

L )
)
x

int x = 8L; // Error: no implicit conversion from long to int


int x = (int)8L; // OK: explicit conversion to int

Namespace
Namespace keyword Object

namespace SampleNamespace
{
class SampleClass { }

interface SampleInterface { }

struct SampleStruct { }

enum SampleEnum { a, b }

delegate void SampleDelegate(int i);

namespace SampleNamespace.Nested
{
class SampleClass2 { }
}
}

another namespace
class
interface
struct
enum
delegate

namespace SomeNameSpace
{
public class MyClass
{
static void Main()
{
Nested.NestedNameSpaceClass.SayHello();
}
}

297 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// a nested namespace
namespace Nested
{
public class NestedNameSpaceClass
{
public static void SayHello()
{
Console.WriteLine("Hello");
}
}
}
}

Hello

New
New keyword operator modifier constraint
new Operator

O create .
new Modifier

B inherited

new Constraint

G

Null

class Program
{
class MyClass
{
public void MyMethod() { }
}

static void Main(string[] args)


{
// Set a breakpoint here to see that mc = null.

298 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// However, the compiler considers it "unassigned."


// and generates a compiler error if you try to
// use the variable.
MyClass mc;

// Now the variable can be used, but...


mc = null;

// ... a method call on a null object raises


// a run-time NullReferenceException.
// Uncomment the following line to see for yourself.
// mc.MyMethod();

// Now mc has a value.


mc = new MyClass();

// You can call its method.


mc.MyMethod();

// Set mc to null again. The object it referenced


// is no longer accsessible and can now be garbage-collected.
mc = null;

// A null string is not the same as an empty string.


string s = null;
string t = String.Empty; // Logically the same as ""

// Equals applied to any null object returns false.


bool b = (t.Equals(s));
Console.WriteLine(b);

// Equality operator also returns false when one


// operand is null.
Console.WriteLine("Empty string {0} null string", s == t ? "equals": "does not
equal");

// Returns true.
Console.WriteLine("null == null is {0}", null == null);

// A value type cannot be null


// int i = null; // Compiler error!

// Use a nullable value type instead:


int? i = null;

// Keep the console window open in debug mode.


System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();

}
}

Object
Object type NET.Framework Object C#
predefined type user-defined type reference type value type object

299 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Object type variable


value Value type
Boxing Object type variable value type Unboxing

Operator
Operator keyword built-in operator overload class
user-defined conversion
built-in operator conversion operator

class Fraction
{
int num, den;
public Fraction(int num, int den)
{
this.num = num;
this.den = den;
}
// overload operator +
public static Fraction operator +(Fraction a, Fraction b)
{
return new Fraction(a.num * b.den + b.num * a.den,
a.den * b.den);
}
// overload operator *
public static Fraction operator *(Fraction a, Fraction b)
{
return new Fraction(a.num * b.num, a.den * b.den);
}
// user-defined conversion from Fraction to double
public static implicit operator double(Fraction f)
{
return (double)f.num / f.den;
}
}
class Test
{
static void Main()
{
Fraction a = new Fraction(1, 2);
Fraction b = new Fraction(3, 7);
Fraction c = new Fraction(2, 3);
Console.WriteLine((double)(a * b + c));
}
}

300 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

0.880952380952381

Out
Out keyword parameter modifier generic type parameter
Generic type parameter out(generic modifier)
Parameter modifier
Arguments reference type pass out keyword
Out keyword ref keyword ref keyword arguments
pass variable initialize(int value=3;) Out keyword variable
initialize(int value ;) Out keyword ref keyword
method name differs from
class CS0663_Example
{
// Compiler error CS0663: "Cannot define overloaded
// methods that differ only on ref and out".
public void SampleMethod(out int i) { }
public void SampleMethod(ref int i) { }
}

class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}

Out (Generic modifier)


Generic interfaces delegates out keyword parameter
G

// Covariant interface.
interface ICovariant<out R> { }

301 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// Extending covariant interface.


interface IExtCovariant<out R> : ICovariant<R> { }

// Implementing covariant interface.


class Sample<R> : ICovariant<R> { }

class Program
{
static void Test()
{
ICovariant<Object> iobj = new Sample<Object>();
ICovariant<String> istr = new Sample<String>();
// You can assign istr to iobj because
// the ICovariant interface is covariance.
iobj = istr;
}
}

Override
Base class method property indexer ( ) event inherit class
Base class method ( ) )
override keyword Override keyword abstract ( ) virtual

abstract class ShapesClass


{
abstract public int Area();
}
class Square : ShapesClass
{
int side = 0;
public Square(int n)
{
side = n;
}
// Area method is required to avoid
// a compile-time error.
public override int Area()
{
return side * side;

302 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
static void Main()
{
Square sq = new Square(12);
Console.WriteLine("Area of the square = {0}", sq.Area());
}
interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}
}

Area of the square = 144

class TestOverride
{
public class Employee
{
public string name;

// Basepay is defined as protected, so that it may be


// accessed only by this class and derrived classes.
protected decimal basepay;
// Constructor to set the name and basepay values.
public Employee(string name, decimal basepay)
{
this.name = name;
this.basepay = basepay;
}
// Declared virtual so it can be overridden.
public virtual decimal CalculatePay()
{
return basepay;
}
}
// Derive a new class from Employee.
public class SalesEmployee : Employee
{

303 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// New field that will affect the base pay.


private decimal salesbonus;
// The constructor calls the base-class version, and
// initializes the salesbonus field.
public SalesEmployee(string name, decimal basepay,
decimal salesbonus) : base(name, basepay)
{
this.salesbonus = salesbonus;
}
// Override the CalculatePay method
// to take bonus into account.
public override decimal CalculatePay()
{
return basepay + salesbonus;
}
}
static void Main()
{
// Create some new employees.
SalesEmployee employee1 = new SalesEmployee("Alice",
1000, 500);
Employee employee2 = new Employee("Bob", 1200);

Console.WriteLine("Employee4 " + employee1.name +


" earned: " + employee1.CalculatePay());
Console.WriteLine("Employee4 " + employee2.name +
" earned: " + employee2.CalculatePay());
}
}

Employee4 Alice earned: 1500


Employee4 Bob earned: 1200

Params
Params keyword arguments
arguments pass argument
,

public class MyClass


{
public static void UseParams(params int[] list)

304 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
public static void UseParams2(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
static void Main()
{
// You can send a comma-separated list of arguments of the
// specified type.
UseParams(1, 2, 3, 4);
UseParams2(1, 'a', "test");
// A params parameter accepts zero or more arguments.
// The following calling statement displays only a blank line.
UseParams2();
// An array argument can be passed, as long as the array
// type matches the parameter type of the method being called.
int[] myIntArray = { 5, 6, 7, 8, 9 };
UseParams(myIntArray);
object[] myObjArray = { 2, 'b', "test", "again" };
UseParams2(myObjArray);
// The following call causes a compiler error because the object
// array cannot be converted into an integer array.
//UseParams(myObjArray);
// The following call does not cause an error, but the entire
// integer array becomes the first element of the params array.
UseParams2(myIntArray);
}
}

1 2 3 4
1 a test

5 6 7 8 9
2 b test again
System.Int32[]

305 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Private
Private keyword access modifier Private
variable class private
variable class

class Employee2
{
private string name = "FirstName, LastName";
private double salary = 100.0;

public string GetName()


{
return name;
}

public double Salary


{
get { return salary; }
}
}
class PrivateTest
{
static void Main()
{
Employee2 e = new Employee2();

// The data members are inaccessible (private), so


// they can't be accessed like this:
// string n = e.name;
// double s = e.salary;

// 'name' is indirectly accessed via method:


string n = e.GetName();

// 'salary' is indirectly accessed via property


double s = e.Salary;
}
}

Protected
Protected keyword access modifier Protected
variable class class derived class

class A
{

306 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

protected int x = 123;


}
class B : A
{
static void Main()
{
A a = new A();
B b = new B();

// Error CS1540, because x can only be accessed by


// classes derived from A.
// a.x = 10;
// OK, because this class derives from A.
b.x = 10;
}
}

Public
Public keyword access modifier Public keyword
Public variable

class PointTest
{
public int x;
public int y;
}
class MainClass4
{
static void Main()
{
PointTest p = new PointTest();
// Direct access to public members:
p.x = 10;
p.y = 15;
Console.WriteLine("x = {0}, y = {1}", p.x, p.y);
}
}

x = 10, y = 15

Readonly

307 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Constant Local variable readonly Keyword


variable Readonly keyword const keyword
Const keywrod Readonly keyword Const field
initialized Readonly field initialized constructor
Const field compile-time readionly run-
time

public class ReadOnlyTest


{
class SampleClass
{
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;

public SampleClass()
{
// Initialize a readonly instance field
z = 24;
}
public SampleClass(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
}
static void Main()
{
SampleClass p1 = new SampleClass(11, 21, 32); // OK
Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
SampleClass p2 = new SampleClass();
p2.x = 55; // OK
Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
}
}

p1: x=11, y=21, z=32


p2: x=55, y=25, z=24

Ref

308 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Arguments reference type pass ref keyword


Method ref argument method argument
pass pass Out keywrod ref keyword ref
keyword arguments pass variable initialize(int value=3;)
Out keyword variable initialize(int value ;)

class RefExample
{
static void Method(ref int i)
{
// Rest the mouse pointer over i to verify that it is an int.
// The following statement would cause a compiler error if i
// were boxed as an object.
i = i + 44;
}
static void Main()
{
int val = 1;
Method(ref val);
Console.WriteLine(val);
}
}

45

Return
Method execute value( )
return keyword Method return keyword
Method return statement
skip

class ReturnTest
{
static double CalculateArea(int r)
{
double area = r * r * Math.PI;
return area;
}
static void Main()

309 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
int radius = 5;
double result = CalculateArea(radius);
Console.WriteLine("The area is {0:0.00}", result);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}

The area is 78.54

Sbyte
Sbyte keyword integral type
range
Type Range Size .NET Framework type
sbyte -128 to 127 Signed 8-bit integer System. SByte

Sbyte

sbyte sByte1 = 127;

Sealed
Sealed keywrod inherit A class B class
inherit B class sealed class B class class
inherit

class X
{
protected virtual void F() { Console.WriteLine("X.F"); }
protected virtual void F2() { Console.WriteLine("X.F2"); }
}
class Y : X
{
sealed protected override void F() { Console.WriteLine("Y.F"); } // Sealed
function
protected override void F2() { Console.WriteLine("X.F3"); }
}
class Z : Y

310 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
// Attempting to override F causes compiler error CS0239.
// protected override void F() { Console.WriteLine("C.F"); } // sealed function

// Overriding F2 is allowed.
protected override void F2() { Console.WriteLine("Z.F2"); }
}

Short
Short keyword integral type
range
Type Range Size .NET Framework type
short -32,768 to 32,767 Signed 16-bit integer System. Int16

Short
short x = 32767;

Short type int, long, float, double, or decimal implicit conversion


Storage sizes integral type explicit
conversion arithmetic expression
variable default integer type
Short type variable x

short x = 5, y = 12;

short z = x + y; // Error: no conversion from int to short

short z = (short)(x + y); // OK: explicit conversion

Sizeof
Data type Data size Sizeof keyword
Sizeof operator overloading Sizeof return

Expression Constant value
sizeof(sbyte) 1
sizeof(byte) 1
sizeof(short) 2

311 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

sizeof(ushort) 2
sizeof(int) 4
sizeof(uint) 4
sizeof(long) 8
sizeof(ulong) 8
sizeof(char) 2 (Unicode)
sizeof(float) 4
sizeof(double) 8
sizeof(decimal) 16
sizeof(bool) 1

class MainClass
{
// unsafe not required for primitive types
static void Main()
{
Console.WriteLine("The size of short is {0}.", sizeof(short));
Console.WriteLine("The size of int is {0}.", sizeof(int));
Console.WriteLine("The size of long is {0}.", sizeof(long));
}
}

The size of short is 2.


The size of int is 4.
The size of long

Stackalloc
Stackalloc keyword unsafe code (unsafe code security
) Stackalloc keyword variable
memory
int* block = stackalloc int[100];

Stackalloc keyword initialize



int* block;
// The following assignment statement causes compiler errors. You

312 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// can use stackalloc only when declaring and initializing a local


// variable.
block = stackalloc int[100];

class Test
{
static unsafe void Main()
{
const int arraySize = 20;
int* fib = stackalloc int[arraySize];
int* p = fib;
// The sequence begins with 1, 1.
*p++ = *p++ = 1;
for (int i = 2; i < arraySize; ++i, ++p)
{
// Sum the previous two numbers.
*p = p[-1] + p[-2];
}
for (int i = 0; i < arraySize; ++i)
{
Console.WriteLine(fib[i]);
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584

313 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

4181
6765

This
This keyword current class
This keyword Fields name Indexers

public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}

public int this[int param]


{
get { return array[param]; }
set { array[param] = value; }
}

class Employee
{
private string name;
private string alias;
private decimal salary = 3000.00m;
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
// Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
}
public decimal Salary
{
get { return salary; }
}

314 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
class Tax
{
public static decimal CalcTax(Employee E)
{
return 0.08m * E.Salary;
}
}
class MainClass
{
static void Main()
{
// Create objects:
Employee E1 = new Employee("Mingda Pan", "mpan");
// Display results:
E1.printEmployee();
}
}

Name: Mingda Pan


Alias: mpan
Taxes: $240.00

Throw
Program execute error Exeception
throw statement Throw singnal
Throw object system.Exception
derive

public class ThrowTest2


{
static int GetNumber(int index)
{
int[] nums = { 300, 600, 900 };
if (index > nums.Length)
{
throw new IndexOutOfRangeException();
}
return nums[index];
}
static void Main()
{
int result = GetNumber(3);

315 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

}
}

The System.IndexOutOfRangeException

True
True keyword voerloading operator ( ) literal

Try
Try-catch statement try block catch clauses
Catch clauses Exceptions

When an exception is thrown, the common language runtime (CLR) looks for the catch
statement that handles this exception. If the currently executing method does not contain such
a catch block, the CLR looks at the method that called the current method, and so on up the
call stack. If no catch block is found, then the CLR displays an unhandled exception message
to the user and stops execution of the program.

The try block contains the guarded code that may cause the exception. The block is executed
until an exception is thrown or it is completed successfully. For example, the following
attempt to cast a null object raises the NullReferenceException exception:
object o2 = null;
try
{
int i2 = (int)o2; // Error
}

Although the catch clause can be used without arguments to catch any type of exception, this
usage is not recommended. In general, you should only catch those exceptions that you know
how to recover from. Therefore, you should always specify an object argument derived from
System. Exception For example:
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
catch (InvalidCastException e)
{
}

316 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

It is possible to use more than one specific catch clause in the same try-catch statement. In
this case, the order of the catch clauses is important because the catch clauses are examined
in order. Catch the more specific exceptions before the less specific ones. The compiler
produces an error if you order your catch blocks so that a later block can never be reached.

A throw statement can be used in a catch block to re-throw the exception that is caught by the
catch statement. The following example extracts source information from an IOException
exception, and then throws the exception to the parent method.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
catch (FileNotFoundException e)
{
// FileNotFoundExceptions are handled here.
}
catch (IOException e)
{
// Extract some information from this exception, and then
// throw it to the parent method.
if (e.Source != null)
Console.WriteLine("IOException source: {0}", e.Source);
throw;
}

You can catch one exception and throw a different exception. When you do this, specify the
exception that you caught as the inner exception, as shown in the following example.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
catch (InvalidCastException e)
{
// Perform some action here, and then throw a new exception.
throw new YourCustomException("Put your error message here.", e);
}

You can also re-throw an exception when a specified condition is true, as shown in the
following example.
JavaScript
C#
C++
F#

317 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

JScript
VB
Copy to Clipboard
catch (InvalidCastException e)
{
if (e.Data == null)
{
throw;
}
else
{
// Take some action.
}
}

From inside a try block, initialize only variables that are declared therein. Otherwise, an
exception can occur before the execution of the block is completed. For example, in the
following code example, the variable n is initialized inside the try block. An attempt to use
this variable outside the try block in the Write(n) statement will generate a compiler error.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
static void Main()
{
int n;
try
{
// Do not initialize this variable here.
n = 123;
}
catch
{
}
// Error: Use of unassigned local variable 'n'.
Console.Write(n);
}

For more information about catch, see try-catch-finally.

Exceptions in Async Methods

An async method is marked by an async modifier and usually contains one or more await
expressions or statements. An await expression applies the await operator to a Task or Task<
TResult> . Anawait expression can't occur in a catch block or a finally block.

When control reaches an await in the async method, progress in the method is suspended
until the awaited task completes. When the task is complete, execution can resume in the

318 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

method. For more information, see Asynchronous Programming with Async and Await (C#
and Visual Basic) and Control Flow in Async Programs (C# and Visual Basic).

The completed task to which await is applied might be in a faulted state because of an
unhandled exception in the method that returns the task. Awaiting the task throws an
exception. A task can also end up in a canceled state if the asynchronous process that returns
it is canceled. Awaiting a canceled task throws an OperationCanceledException. For more
information about how to cancel an asynchronous process, see Fine Tuning Your Async
Application (C# and Visual Basic).

To catch the exception, await the task in a try block, and catch the exception in the associated
catch block. For an example, see the "Example" section.

A task can be in a faulted state because multiple exceptions occurred in the awaited async
method. For example, the task might be the result of a call to Task. WhenAll. When you
await such a task, only one of the exceptions is caught, and you can't predict which exception
will be caught. For an example, see the "Example" section.

Example

In the following example, the try block contains a call to the ProcessString method that may
cause an exception. The catch clause contains the exception handler that just displays a
message on the screen. When the throw statement is called from inside MyMethod, the
system looks for the catch statement and displays the message Exception caught.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
class TryFinallyTest
{
static void ProcessString(string s)
{
if (s == null)
{
throw new ArgumentNullException();
}
}

static void Main()


{
string s = null; // For demonstration purposes.

try
{
ProcessString(s);
}

319 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
/*
Output:
System.ArgumentNullException: Value cannot be null.
at TryFinallyTest.Main() Exception caught.
* */

In the following example, two catch blocks are used, and the most specific exception, which
comes first, is caught.

To catch the least specific exception, you can replace the throw statement in ProcessString
with the following statement: throw new Exception().

If you place the least-specific catch block first in the example, the following error message
appears: A previous catch clause already catches all exceptions of this or a super type
('System.Exception').
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
class ThrowTest3
{
static void ProcessString(string s)
{
if (s == null)
{
throw new ArgumentNullException();
}
}

static void Main()


{
try
{
string s = null;
ProcessString(s);
}
// Most specific:
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
}
// Least specific:
catch (Exception e)
{

320 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.WriteLine("{0} Second exception caught.", e);


}
}
}
/*
Output:
System.ArgumentNullException: Value cannot be null.
at Test.ThrowTest3.ProcessString(String s) ... First exception caught.
*/

The following example illustrates exception handling for async methods. To catch an
exception that applies to an async task, place the await expression in a try block, and catch
the exception in a catch block.

Uncomment the throw new Exception line in the example to demonstrate exception handling.
The task's IsFaulted property is set to True, the task's Exception.InnerException property is
set to the exception, and the exception is caught in the catch block.

Uncomment the throw new OperationCancelledException line to demonstrate what happens


when you cancelan asynchronous process. The task's IsCanceled property is set to true, and
the exception is caught in the catch block. Under some conditions that don't apply to this
example, the task's IsFaulted property is set to true and IsCanceled is set to false.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
public async Task DoSomethingAsync()
{
Task<string> theTask = DelayAsync();

try
{
string result = await theTask;
Debug.WriteLine("Result: " + result);
}
catch (Exception ex)
{
Debug.WriteLine("Exception Message: " + ex.Message);
}
Debug.WriteLine("Task IsCanceled: " + theTask.IsCanceled);
Debug.WriteLine("Task IsFaulted: " + theTask.IsFaulted);
if (theTask.Exception != null)
{
Debug.WriteLine("Task Exception Message: "
+ theTask.Exception.Message);
Debug.WriteLine("Task Inner Exception Message: "
+ theTask.Exception.InnerException.Message);
}
}

321 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

private async Task<string> DelayAsync()


{
await Task.Delay(100);

// Uncomment each of the following lines to


// demonstrate exception handling.

//throw new OperationCanceledException("canceled");


//throw new Exception("Something happened.");
return "Done";
}

// Output when no exception is thrown in the awaited method:


// Result: Done
// Task IsCanceled: False
// Task IsFaulted: False

// Output when an Exception is thrown in the awaited method:


// Exception Message: Something happened.
// Task IsCanceled: False
// Task IsFaulted: True
// Task Exception Message: One or more errors occurred.
// Task Inner Exception Message: Something happened.

// Output when a OperationCanceledException or


TaskCanceledException
// is thrown in the awaited method:
// Exception Message: canceled
// Task IsCanceled: True
// Task IsFaulted: False

The following example illustrates exception handling where multiple tasks can result in
multiple exceptions. The try block awaits the task that's returned by a call to Task. WhenAll.
The task is complete when the three tasks to which WhenAll is applied are complete.

Each of the three tasks causes an exception. The catch block iterates through the exceptions,
which are found in the Exception.InnerExceptions property of the task that was returned by
Task. WhenAll.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
public async Task DoMultipleAsync()
{
Task theTask1 = ExcAsync(info: "First Task");
Task theTask2 = ExcAsync(info: "Second Task");
Task theTask3 = ExcAsync(info: "Third Task");

Task allTasks = Task.WhenAll(theTask1, theTask2, theTask3);

try

322 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
await allTasks;
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message);
Debug.WriteLine("Task IsFaulted: " + allTasks.IsFaulted);
foreach (var inEx in allTasks.Exception.InnerExceptions)
{
Debug.WriteLine("Task Inner Exception: " + inEx.Message);
}
}
}

private async Task ExcAsync(string info)


{
await Task.Delay(100);

throw new Exception("Error-" + info);


}

// Output:
// Exception: Error-First Task
// Task IsFaulted: True
// Task Inner Exception: Error-First Task
// Task Inner Exception: Error

Static

Use the static modifier to declare a static member, which belongs to the type itself
rather than to a specific object. The static modifier can be used with classes, fields, methods,
properties, operators, events, and constructors, but it cannot be used with indexers,
destructors, or types other than classes. For more information, see Static Classes and Static
Class Members (C# Programming Guide).

Example

The following class is declared as static and contains only static methods:
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard

323 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

static class CompanyEmployee


{
public static void DoSomething() { /*...*/ }
public static void DoSomethingElse() { /*...*/ }
}

A constant or type declaration is implicitly a static member.

A static member cannot be referenced through an instance. Instead, it is referenced through the
type name. For example, consider the following class:
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
public class MyBaseC
{
public struct MyStruct
{
public static int x = 100;
}
}

To refer to the static member x, use the fully qualified name, MyBaseC.MyStruct.x, unless the
member is accessible from the same scope:
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
Console.WriteLine(MyBaseC.MyStruct.x);

While an instance of a class contains a separate copy of all instance fields of the class, there is only
one copy of each static field.

It is not possible to use this to reference static methods or property accessors.

If the static keyword is applied to a class, all the members of the class must be static.

Classes and static classes may have static constructors. Static constructors are called at some point
between when the program starts and the class is instantiated.

324 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Note
The static keyword has more limited uses than in C++. To compare with the C++ keyword, see Static
(C++).

To demonstrate static members, consider a class that represents a company employee. Assume that
the class contains a method to count employees and a field to store the number of employees. Both
the method and the field do not belong to any instance employee. Instead they belong to the
company class. Therefore, they should be declared as static members of the class.

This example reads the name and ID of a new employee, increments the employee counter by one,
and displays the information for the new employee and the new number of employees. For
simplicity, this program reads the current number of employees from the keyboard. In a real
application, this information should be read from a file.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
public class Employee4
{
public string id;
public string name;

public Employee4()
{
}

public Employee4(string name, string id)


{
this.name = name;
this.id = id;
}

public static int employeeCounter;

public static int AddEmployee()


{
return ++employeeCounter;
}
}

class MainClass : Employee4


{
static void Main()

325 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

{
Console.Write("Enter the employee's name: ");
string name = Console.ReadLine();
Console.Write("Enter the employee's ID: ");
string id = Console.ReadLine();

// Create and configure the employee object:


Employee4 e = new Employee4(name, id);
Console.Write("Enter the current number of employees: ");
string n = Console.ReadLine();
Employee4.employeeCounter = Int32.Parse(n);
Employee4.AddEmployee();

// Display the new information:


Console.WriteLine("Name: {0}", e.name);
Console.WriteLine("ID: {0}", e.id);
Console.WriteLine("New Number of Employees: {0}",
Employee4.employeeCounter);
}
}
/*
Input:
Matthias Berndt
AF643G
15
*
Sample Output:
Enter the employee's name: Matthias Berndt
Enter the employee's ID: AF643G
Enter the current number of employees: 15
Name: Matthias Berndt
ID: AF643G
New Number of Employees: 16
*/

This example shows that although you can initialize a static field by using another static field not yet
declared, the results will be undefined until you explicitly assign a value to the static field.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
class Test
{
static int x = y;
static int y = 5;

326 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

static void Main()


{
Console.WriteLine(Test.x);
Console.WriteLine(Test.y);

Test.x = 99;
Console.WriteLine(Test.x);
}
}
/*
Output:

String

The string type represents a sequence of zero or more Unicode characters. string is an alias for String
in the .NET Framework.

Although string is a reference type, the equality operators (== and !=) are defined to compare the
values of string objects, not references. This makes testing for string equality more intuitive. For
example:
Copy to Clipboard
string a = "hello";
string b = "h";
// Append to contents of 'b'
b += "ello";
Console.WriteLine(a == b);
Console.WriteLine((object)a == (object)b);

This displays "True" and then "False" because the content of the strings are equivalent, but a and b
do not refer to the same string instance.

The + operator concatenates strings:


Copy to Clipboard
string a = "good " + "morning";

This creates a string object that contains "good morning".

Strings are immutable--the contents of a string object cannot be changed after the object is created,
although the syntax makes it appear as if you can do this. For example, when you write this code,
the compiler actually creates a new string object to hold the new sequence of characters, and that
new object is assigned to b. The string "h" is then eligible for garbage collection.
Copy to Clipboard
string b = "h";
b += "ello";

327 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

The [] operator can be used for readonly access to individual characters of a string:
Copy to Clipboard
string str = "test";
char x = str[2]; // x = 's';

String literals are of type string and can be written in two forms, quoted and @-quoted. Quoted
string literals are enclosed in double quotation marks ("):
Copy to Clipboard
"good morning" // a string literal

String literals can contain any character literal. Escape sequences are included. The following
example uses escape sequence \\ for backslash, \u0066 for the letter f, and \n for newline.
Copy to Clipboard
string a = "\\\u0066\n";
Console.WriteLine(a);

Note
The escape code \udddd (where dddd is a four-digit number) represents the Unicode character
U+dddd. Eight-digit Unicode escape codes are also recognized: \Udddddddd.

Verbatim string literals start with @ and are also enclosed in double quotation marks. For example:
Copy to Clipboard
@"good morning" // a string literal

The advantage of verbatim strings is that escape sequences are not processed, which makes it easy
to write, for example, a fully qualified file name:
Copy to Clipboard
@"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"

To include a double quotation mark in an @-quoted string, double it:


Copy to Clipboard
@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.

Another use of the @ symbol is to use referenced ( /reference) identifiers that are C# keywords.

For more information about strings in C#, see Strings (C# Programming Guide).

Example

JavaScript
C#
C++
F#
JScript
VB

328 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Copy to Clipboard
class SimpleStringTest
{
static void Main()
{
string a = "\u0068ello ";
string b = "world";
Console.WriteLine( a + b );
Console.WriteLine( a + b == "Hello World" ); // == performs a case-
sensitive comparison
}
}
/* Output:
hello world
False

Struct

A struct type is a value type that is typically used to encapsulate small groups of related variables,
such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following
example shows a simple struct declaration:
Copy to Clipboard
public struct Book
{
public decimal price;
public string title;
public string author;
}

Remarks

Structs can also contain constructors, constants, fields, methods, properties, indexers, operators,
events, and nested types, although if several such members are required, you should consider
making your type a class instead.

Structs can implement an interface but they cannot inherit from another struct. For that reason,
struct members cannot be declared as protected.

For more information, see Structs (C# Programming Guide).

Switch

329 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

The switch statement is a control statement that selects a switch section to execute from a list
of candidates.

Each switch section contains one or more case labels and a list of one or more statements.
The following example shows a simple switch statement that has three switch sections. Each
switch section has one case label, such as case 1, and a list of two statements.

Example

JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}

Each case label specifies a constant value. Control is transferred to the switch section whose
case label contains a constant value that matches the value of the switch expression,
caseSwitch. If no case label contains a matching value, control is transferred to the default
section, if there is one. If there is no default section, no action is taken and control is
transferred outside the switch statement. In the previous example, the statements in the first
switch section are executed because case label case 1 specifies the value 1, and the value of
caseSwitch also is 1.

A switch statement can include any number of switch sections, and each section can have one
or more case labels. However, no two case labels can contain the same constant value.

Execution of the statement list in the selected section begins with the first statement and
proceeds through the statement list, typically until a jump statement is reached, such as a
break, goto case, return, or throw. At that point, control is transferred outside the switch
statement or to another case label.

Unlike C++, C# does not allow execution to continue from one switch section to the next.
The following code causes an error.
JavaScript

330 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

C#
C++
F#
JScript
VB
Copy to Clipboard
switch (caseSwitch)
{
// The following switch section causes an error.
case 1:
Console.WriteLine("Case 1...");
// Add a break or other jump statement here.
case 2:
Console.WriteLine("... and/or Case 2");
break;
}

The requirement in C# is that the end of every switch section, including the final one, is
unreachable. Although this requirement usually is met by using a jump statement, the
following case also is valid, because the end of the statement list cannot be reached.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
case 4:
while (true)
Console.WriteLine("Endless looping. . . .");

The following example illustrates the requirements and capabilities of a switch statement.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
class Program
{
static void Main(string[] args)
{
int switchExpression = 3;
switch (switchExpression)
{
// A switch section can have more than one case label.
case 0:
case 1:
Console.WriteLine("Case 0 or 1");

331 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

// Most switch sections contain a jump statement, such as


// a break, goto, or return. The end of the statement list
// must be unreachable.
break;
case 2:
Console.WriteLine("Case 2");
break;
// The following line causes a warning.
Console.WriteLine("Unreachable code");
// 7 - 4 in the following line evaluates to 3.
case 7 - 4:
Console.WriteLine("Case 3");
break;
// If the value of switchExpression is not 0, 1, 2, or 3, the
// default case is executed.
default:
Console.WriteLine("Default case (optional)");
// You cannot "fall through" any switch section, including
// the last one.
break;
}
}
}

In the final example, string input is converted to an integer variable, switchExp, which is used
for the switch expression. You also can use the string variable, str, directly. To do that, you
would change the case labels to specify string values, as is shown in the following code.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
switch(str)
{
case "1":
// ...
case "2":
// ...
}
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
class SwitchTest
{
static void Main()
{
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");

332 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Console.Write("Please enter your selection: ");


string str = Console.ReadLine();
int switchExp = int.Parse(str);
int cost = 0;
switch (switchExp)
{
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
case 3:
cost += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection. Please select 1, 2,
or 3.");
break;
}
if (cost != 0)
{
Console.WriteLine("Please insert {0} cents.", cost);
}
Console.WriteLine("Thank you for your business.");
}
}
/*
Sample Input: 2

Sample Output:

Typeof

Used to obtain the System.Type object for a type. A typeof expression takes the following form:
Copy to Clipboard
System.Type type = typeof(int);

Remarks

To obtain the run-time type of an expression, you can use the .NET Framework method GetType, as
in the following example:
Copy to Clipboard
int i = 0;
System.Type type = i.GetType();

The typeof operator cannot be overloaded.

The typeof operator can also be used on open generic types. Types with more than one type
parameter must have the appropriate number of commas in the specification. The following

333 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

example shows how to determine whether the return type of a method is a generic IEnumerable< T>
. Assume that method is an instance of a MethodInfo type:
Copy to Clipboard
string s = method.ReturnType.GetInterface
(typeof(System.Collections.Generic.IEnumerable<>).FullName);

Example

JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
public class ExampleClass
{
public int sampleMember;
public void SampleMethod() {}

static void Main()


{
Type t = typeof(ExampleClass);
// Alternatively, you could use
// ExampleClass obj = new ExampleClass();
// Type t = obj.GetType();

Console.WriteLine("Methods:");
System.Reflection.MethodInfo[] methodInfo = t.GetMethods();

foreach (System.Reflection.MethodInfo mInfo in methodInfo)


Console.WriteLine(mInfo.ToString());

Console.WriteLine("Members:");
System.Reflection.MemberInfo[] memberInfo = t.GetMembers();

foreach (System.Reflection.MemberInfo mInfo in memberInfo)


Console.WriteLine(mInfo.ToString());
}
}
/*
Output:
Methods:
Void SampleMethod()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
Members:

334 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Void SampleMethod()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
Void .ctor()
Int32 sampleMember
*/

This sample uses the GetType method to determine the type that is used to contain the result of a
numeric calculation. This depends on the storage requirements of the resulting number.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard

Unit

The uint keyword signifies an integral type that stores values according to the size and range shown
in the following table.
Type Range Size .NET Framework type
uint 0 to 4,294,967,295 Unsigned 32-bit integer System. UInt32

Note The uint type is not CLS-compliant. Use int whenever possible.

Literals

You can declare and initialize a variable of the type uint like this example:
Copy to Clipboard
uint myUint = 4294967290;

When an integer literal has no suffix, its type is the first of these types in which its value can be
represented: int, uint, long, ulong. In this example, it is uint:
Copy to Clipboard
uint uInt1 = 123;

You can also use the suffix u or U, such as this:

335 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Copy to Clipboard
uint uInt2 = 123U;

When you use the suffix U or u, the type of the literal is determined to be either uint or ulong
according to the numeric value of the literal. For example:
Copy to Clipboard
Console.WriteLine(44U.GetType());
Console.WriteLine(323442434344U.GetType());

This code displays System.UInt32, followed by System.UInt64 -- the underlying types for uint and
ulong respectively -- because the second literal is too large to be stored by the uint type.

Conversions

There is a predefined implicit conversion from uint to long, ulong, float, double, or decimal. For
example:
Copy to Clipboard
float myFloat = 4294967290; // OK: implicit conversion to float

There is a predefined implicit conversion from byte, ushort, or char to uint. Otherwise you must use
a cast. For example, the following assignment statement will produce a compilation error without a
cast:
Copy to Clipboard
long aLong = 22;
// Error -- no implicit conversion from long:
uint uInt1 = aLong;
// OK -- explicit conversion:
uint uInt2 = (uint)aLong;

Notice also that there is no implicit conversion from floating-point types to uint. For example, the
following statement generates a compiler error unless an explicit cast is used:
Copy to Clipboard
// Error -- no implicit conversion from double:
uint x = 3.0;
// OK -- explicit conversion:
uint y = (uint)3.0;

For information about arithmetic expressions with mixed floating-point types and integral types, see
float and double.

For more information about implicit numeric conversion rules, see the Implicit Numeric Conversions
Table (C# Reference).

336 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Ulong

The ulong keyword denotes an integral type that stores values according to the size and range
shown in the following table.
Type Range Size .NET Framework type
ulong 0 to 18,446,744,073,709,551,615 Unsigned 64-bit integer System. UInt64

Literals

You can declare and initialize a ulong variable like this example:
Copy to Clipboard
ulong uLong = 9223372036854775808;

When an integer literal has no suffix, its type is the first of these types in which its value can be
represented: int, uint, long, ulong. In the example above, it is of the type ulong.

You can also use suffixes to specify the type of the literal according to the following rules:

If you use L or l, the type of the literal integer will be either long or ulong according to its
size.

Note
You can use the lowercase letter "l" as a suffix. However, this generates a compiler warning
because the letter "l" is easily confused with the digit "1." Use "L" for clarity.

If you use U or u, the type of the literal integer will be either uint or ulong according to its
size.
If you use UL, ul, Ul, uL, LU, lu, Lu, or lU, the type of the literal integer will be ulong.

For example, the output of the following three statements will be the system type UInt64,
which corresponds to the alias ulong:

Copy to Clipboard
Console.WriteLine(9223372036854775808L.GetType());
Console.WriteLine(123UL.GetType());
Console.WriteLine((123UL + 456).GetType());

A common use of the suffix is with calling overloaded methods. Consider, for example, the following
overloaded methods that use ulong and int parameters:
Copy to Clipboard
public static void SampleMethod(int i) {}

337 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

public static void SampleMethod(ulong l) {}

Using a suffix with the ulong parameter guarantees that the correct type is called, for example:
Copy to Clipboard
SampleMethod(5); // Calling the method with the int parameter
SampleMethod(5UL); // Calling the method with the ulong parameter

Conversions

There is a predefined implicit conversion from ulong to float, double, or decimal.

There is no implicit conversion from ulong to any integral type. For example, the following statement
will produce a compilation error without an explicit cast:
Copy to Clipboard
long long1 = 8UL; // Error: no implicit conversion from ulong

There is a predefined implicit conversion from byte, ushort, uint, or char to ulong.

Also, there is no implicit conversion from floating-point types to ulong. For example, the following
statement generates a compiler error unless an explicit cast is used:
Copy to Clipboard
// Error -- no implicit conversion from double:
ulong x = 3.0;
// OK -- explicit conversion:
ulong y = (ulong)3.0;

Unchecked

The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic


operations and conversions.

In an unchecked context, if an expression produces a value that is outside the range of the
destination type, the overflow is not flagged. For example, because the calculation in the following
example is performed in an unchecked block or expression, the fact that the result is too large for an
integer is ignored, and int1 is assigned the value -2,147,483,639.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard

338 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

unchecked
{
int1 = 2147483647 + 10;
}
int1 = unchecked(ConstantMax + 10);

If the unchecked environment is removed, a compilation error occurs. The overflow can be detected
at compile time because all the terms of the expression are constants.

Expressions that contain non-constant terms are unchecked by default at compile time and run time.
See checked (C# Reference) for information about enabling a checked environment.

Because checking for overflow takes time, the use of unchecked code in situations where there is no
danger of overflow might improve performance. However, if overflow is a possibility, a checked
environment should be used.

Example

This sample shows how to use the unchecked keyword.


JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard

Unsafe

The unsafe keyword denotes an unsafe context, which is required for any operation involving
pointers. For more information, see Unsafe Code and Pointers (C# Programming Guide).

You can use the unsafe modifier in the declaration of a type or a member. The entire textual extent
of the type or member is therefore considered an unsafe context. For example, the following is a
method declared with the unsafe modifier:
Copy to Clipboard
unsafe static void FastCopy(byte[] src, byte[] dst, int count)
{
// Unsafe context: can use pointers here.
}

339 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

The scope of the unsafe context extends from the parameter list to the end of the method, so
pointers can also be used in the parameter list:
Copy to Clipboard
unsafe static void FastCopy ( byte* ps, byte* pd, int count ) {...}

You can also use an unsafe block to enable the use of an unsafe code inside this block. For example:
Copy to Clipboard
unsafe
{
// Unsafe context: can use pointers here.
}

To compile unsafe code, you must specify the /unsafe compiler option. Unsafe code is not verifiable
by the common language runtime.

Example

JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
// compile with: /unsafe

class UnsafeTest
{
// Unsafe method: takes pointer to int:
unsafe static void SquarePtrParam(int* p)
{
*p *= *p;
}

unsafe static void Main()


{
int i = 5;
// Unsafe method: uses address-of operator (&):
SquarePtrParam(&i);
Console.WriteLine(i);
}
}
// Output: 25

340 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

Ushort

The ushort keyword indicates an integral data type that stores values according to the size and range
shown in the following table.
Type Range Size .NET Framework type
ushort 0 to 65,535 Unsigned 16-bit integer System. UInt16

Literals

You can declare and initialize a ushort variable such as this example:
Copy to Clipboard
ushort myShort = 65535;

In the previous declaration, the integer literal 65535 is implicitly converted from int to ushort. If the
integer literal exceeds the range of ushort, a compilation error will occur.

A cast must be used when you call overloaded methods. Consider, for example, the following
overloaded methods that use ushort and int parameters:
Copy to Clipboard
public static void SampleMethod(int i) {}
public static void SampleMethod(ushort s) {}

Using the ushort cast guarantees that the correct type is called, for example:
Copy to Clipboard
// Calls the method with the int parameter:
SampleMethod(5);
// Calls the method with the ushort parameter:
SampleMethod((ushort)5);

Conversions

There is a predefined implicit conversion from ushort to int, uint, long, ulong, float, double, or
decimal.

There is a predefined implicit conversion from byte or char to ushort. Otherwise a cast must be used
to perform an explicit conversion. Consider, for example, the following two ushort variables x and y:
Copy to Clipboard
ushort x = 5, y = 12;

The following assignment statement will produce a compilation error, because the arithmetic
expression on the right side of the assignment operator evaluates to int by default.
Copy to Clipboard
ushort z = x + y; // Error: conversion from int to ushort

341 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

To fix this problem, use a cast:


Copy to Clipboard
ushort z = (ushort)(x + y); // OK: explicit conversion

It is possible though to use the following statements, where the destination variable has the same
storage size or a larger storage size:
Copy to Clipboard
int m = x + y;
long n = x + y;

Notice also that there is no implicit conversion from floating-point types to ushort. For example, the
following statement generates a compiler error unless an explicit cast is used:
Copy to Clipboard

Using

The using keyword has two major uses:

As a directive, when it is used to create an alias for a namespace or to import types defined
in other namespaces. See using Directive.
As a statement, when it defines a scope at the end of which an object will be disposed. See
using Statement.

Virtual

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow
for it to be overridden in a derived class. For example, this method can be overridden by any class
that inherits it:
Copy to Clipboard
public virtual double Area()
{
return x * y;
}

The implementation of a virtual member can be changed by an overriding member in a derived class.
For more information about how to use the virtual keyword, see Versioning with the Override and
New Keywords (C# Programming Guide) and Knowing When to Use Override and New Keywords (C#
Programming Guide).

Remarks

342 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

When a virtual method is invoked, the run-time type of the object is checked for an overriding
member. The overriding member in the most derived class is called, which might be the original
member, if no derived class has overridden the member.

By default, methods are non-virtual. You cannot override a non-virtual method.

You cannot use the virtual modifier with the static, abstract, private, or override modifiers. The
following example shows a virtual property:
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
class MyBaseClass
{
// virtual auto-implemented property. Overrides can only
// provide specialized behavior if they implement get and set
accessors.
public virtual string Name { get; set; }

// ordinary virtual property with backing field


private int num;
public virtual int Number
{
get { return num; }
set { num = value; }
}
}

class MyDerivedClass : MyBaseClass


{
private string name;

// Override auto-implemented property with ordinary property


// to provide specialized accessor behavior.
public override string Name
{
get
{
return name;
}
set
{

343 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

if (value != String.Empty)
{
name = value;
}
else
{
name = "Unknown";
}
}
}

Void

Virtual properties behave like abstract methods, except for the differences in declaration and
invocation syntax.

It is an error to use the virtual modifier on a static property.


A virtual inherited property can be overridden in a derived class by including a property
declaration that uses the override modifier.

Example

In this example, the Shape class contains the two coordinates x, y, and the Area() virtual method.
Different shape classes such as Circle, Cylinder, and Sphere inherit the Shape class, and the surface
area is calculated for each figure. Each derived class has it own override implementation of Area().

Notice that the inherited classes Circle, Sphere, and Cylinder all use constructors that initialize the
base class, as shown in the following declaration.
Copy to Clipboard
public Cylinder(double r, double h): base(r, h) {}

The following program calculates and displays the appropriate area for each figure by invoking the
appropriate implementation of the Area() method, according to the object that is associated with
the method.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard

344 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

When used as the return type for a method, void specifies that the method does not return a
value.

void is not allowed in the parameter list of a method. A method that takes no parameters and
returns no value is declared as follows:
Copy to Clipboard
void SampleMethod();

void is also used in an unsafe context to declare a pointer to an unknown type. For more
information, see Pointer types (C# Programming Guide).

void is an alias for the .NET Framework System. Void type.

Volatile

The volatile keyword indicates that a field might be modified by multiple threads that are executing
at the same time. Fields that are declared volatile are not subject to compiler optimizations that
assume access by a single thread. This ensures that the most up-to-date value is present in the field
at all times.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the
lock statement to serialize access.

The volatile keyword can be applied to fields of these types:

Reference types.
Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the
object that it points to cannot. In other words, you cannot declare a "pointer to volatile."
Types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
An enum type with one of the following base types: byte, sbyte, short, ushort, int, or uint.
Generic type parameters known to be reference types.
IntPtr and UIntPtr.

The volatile keyword can only be applied to fields of a class or struct. Local variables cannot be
declared volatile.

Example

345 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

The following example shows how to declare a public field variable as volatile.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
class VolatileTest
{
public volatile int i;

public void Test(int _i)


{
i = _i;
}
}

The following example demonstrates how an auxiliary or worker thread can be created and used to
perform processing in parallel with that of the primary thread. For background information about
multithreading, see Managed Threading and Threading (C# and Visual Basic).
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard

While

The while statement executes a statement or a block of statements until a specified expression
evaluates to false.

Example

JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard

346 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

class WhileTest
{
static void Main()
{
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
}
}
/*
Output:
Current value of n is 1
Current value of n is 2
Current value of n is 3
Current value of n is 4
Current value of n is 5
*/
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
class WhileTest2
{
static void Main()
{
int n = 1;
while (n++ < 6)
{
Console.WriteLine("Current value of n is {0}", n);
}
}
}
/*
Output:
Current value of n is 2
Current value of n is 3
Current value of n is 4
Current value of n is 5
Current value of n is 6
*/

Because the test of the while expression takes place before each execution of the loop, a while loop
executes zero or more times. This differs from the do loop, which executes one or more times.

347 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup


C# Tutorials | Process Myanmar Group

A while loop can be terminated when a break, goto, return, or throw statement transfers control
outside the loop. To pass control to the next iteration without exiting the loop, use the continue
statement. Notice the difference in output in the three previous examples, depending on where int n
is incremented. In the example below no output is generated.
JavaScript
C#
C++
F#
JScript
VB
Copy to Clipboard
class WhileTest3
{
static void Main()
{
int n = 5;
while (++n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
}

348 | P a g e C# TUTORIALS F O R BEGINNER By Processgroup

You might also like