Professional Documents
Culture Documents
C Sharp Basic All PDF
C Sharp Basic All PDF
P C# Professional
language
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
C# program
C# .Netframework .Net Application C#
program Running .Netframework C#
.Netframework
.Net framework
C#
C++
Visual Basic
Jscript
J# Programming Language Support )
.Netframework Revolutionay Platform
.Netframework Programming Language
C#
code Program VB code
.Netframework
Windows application
Web application
Web services
Language C# Project
Library of Codes
-
downloadLink Compiler
) S A I B S A )
F I
F S F S )
Select A
) I S B
S A
) S S C
I
) V S C S C
LA NCH Visual Studion program
) Create P
() Visual C# windows
() Console Application
() namespaces
( ) namespaces
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/*my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
static void Main(string[] args): static void Main methodMain C# program entry
point (program ) Class methodMain
execute method
programer
program comment single commet mulitple
comment commet multiple commet single
comment //
C# C S
Statements Ex ;
program Main method
File name Class name (Java )
Visual Studio
Menu bar File New Project
Template window Visual C#
Console Application
Project Name Ok button Click
Solution Explorer P
code E
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 )
Class
width
width
length
length
Object1 Object2
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();
}
}
}
Identifiers
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
Contextual Keywords
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;
Value Types
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();
}
}
Reference Types
i 1 s
Hello
J 2 s1
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;
Console.ReadLine();
}
}
}
Values: 0, 123
Object Types
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
String Types
Pointer Types
Type* <Identifier>;
char* cptr;
int* iptr;
using System;
namespace TypeConvertion
{
Class convertion
{
}
}
}
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
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 (=)
Variable initialization
program Variable
namespace VariableDeclaration
{
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
int num;
num = Convert.ToInt32(Console.ReadLine());
int g = 20;
statement C#
variable g L 20 equal ( = )
L g 20 g 20
Lvalues ( = )
Rvalues (=)
Statement Rvalue
statement compile-time error
10 = 20;
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 */
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
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 */
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
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;
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
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
- A B -10
* A * B 200
/ B / A 2
% 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
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
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");
}
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");
}
}
}
Logical Operators
C# Logical oprator A
B True False True B False
Operator Description Example
(A && B)
&&
condition (false)
true ( )
condition
( )
( )
(A || B)
|| condition true
(true)
condition
( ) ture ( ) !(A && B)
!
(true)
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();
}
}
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 = 0011 1101
A ^ B = 0011 0001
~A = 1100 0011
Bitwise Operator
A B 63 13
Operator Description Example
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 */
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
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;
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;
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));
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
Operator precedence ( )
Category Operator Associativity
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);
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
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
Condition
if condition is
if condition is
false
true
Conditionl
code
Statement Description
if statement boolean ( ( ) (true/flase) )
Expression statement if statement
expression (true) statement (if
if statement { } )code
(false) if
statement if statement
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 statement / (boolean expression) { } code
( ) statement { } code ( )
statement if statement
if condition is true
Condition
if condition is false
If code
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 (boolean expression)
{
// { } statement ( ) statement
// bollean expression (true) statement
//
}
else
{
// bollean expression ) else { }
// statement (true)
// if { } else
}
using System;
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();
}
}
}
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");
}
Console.WriteLine("Exact value of a is: {0}", a);
Console.ReadLine();
}
}
}
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 / */
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();
}
}
}
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 */
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
expression
code block 1
code block 2
code block 3
using System;
namespace switchStatement
{
class Program
{
static void Main(string[] args)
{
Well done
Your grade is B
//nested switch
//the ?: operator
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);
}
Init
if condition
is false
Conditiona
l Code
if condition
is true
Code Block
Increment
Looping C# looping
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)
{
statement(s);
}
While (condition )
{
Codition Code ;
}
Condition
if condition is true
Code Block
if condition is false
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
Condition
if condition if condition
is true is false
Code Block
Increment
using System;
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
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
{
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
using System;
namespace foreachLoop
{
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
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
Nested foreach loop
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();
}
}
}
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
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
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();
}
}
}
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
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 */
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
using System;
namespace infiniteloop
{
class myinfinite
{
static void Main(string[] args)
{
for (; ; )
{
Console.WriteLine("Hey! I am Trapped");
}
}
}
}
Access Specifiers
Access Specier E
Access Specifier Member Variable ( ) Member Function
member variable
C# Access Specifier ()
Access Specifier
-
Protected class
Class Base
Derived Class
Private class
using System;
using System.Collections.Generic;
using System.Text;
namespace encapsulation
{
class Rectangle
{
//member variables
public double length;
public double width;
class publicaccessspecifier
{
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
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
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()
{
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
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
(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
...
class NumbersManiPulator
{
public int FindMaxNumber(int num1, int num2)
{
/* local variables declaration */
int result;
if (num1 > num2)
result = num1;
else result = num2;
return result;
}
}
...
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();
}
}
}
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();
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
Value Parameter
using System;
namespace ValueParameters
{
class NumberManiPulator
{
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();
}
}
}
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();
}
}
}
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();
}
}
}
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;
Console.ReadLine();
}
}
}
using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
}
}
}
Declearing Array
C# Array
Datatype[] arrayName;
double [] myarray;
Initializaing an Array
array Declear
array array
initializating array (size)
(initialize ) array value (assign)
Array reference type array
Initilize new keyword
Assigning an Array
Array (values) (asign)
double[] myarray = new double[10];
myarray[0] = 1200.0;
Values ( ) Array
assign initilize
int[] myarray = new int[5] { 22, 43, 33, 12, 91 };
10 myarray Array
Declear , Initilize
Array Delearation ,assignment
using System;
namespace ArrayApplication
{
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 System;
namespace ConsoleApplication1
{
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
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]
element
coloum x Row Coloum
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]);
}
}
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
using System;
namespace Jagged_Array
{
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
using System;
namespace Passing_arrays_to_functions
{
class MyArray
{
Param Array
Passing Array to fucntions P Array (size)
( )
Passing Param array Param array
param
Array P
using System;
namespace Param_Array
{
class ParamArray
{
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();
}
}
}
LongLength
4 Array Dimension (size) Get size 64-bit
integer
Rank
5
Array Diemsion Get
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 + " ");
}
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
String variable -
using System;
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mystring
{
class Program
{
static void Main(string[] args)
{
if (String.Compare(str1, str2) == 0)
{
Console.WriteLine(str1 + " and " + str2 + " are equal.");
}
else
{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey();
}
}
}
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();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mystring
{
class Program
{
San Pedro
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
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;
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# structure -
class
Class Vs Structure
Class Structure
Structure (inheritance)
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();
Console.ReadKey();
}
}
}
Title : C# Tutorials
author : Process Group
subject : Programming
book_id : 989771
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
{
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main(string[] args)
{
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Monday : 1
Friday : 5
Class Definition
Class Class Keyword
name Class Body curly braces { } )
Class
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
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();
}
}
}
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;
}
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();
}
}
}
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");
}
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();
}
}
}
Destructors in C#
Destructors Class F Object close
Destructors executed Destructors name Class Name
~) Program Flie Memory Release
Destructors Destructors Inherit
Overloading Program
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");
}
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();
}
}
}
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
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);
Total area: 35
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();
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;
}
}
// Derived class
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;
}
}
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
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
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)
{
Total area: 35
Total paint cost: $2450
using System;
namespace PolymorphismApplication1
{
abstract class Shape
{
public abstract int area();
}
class Rectangle: Shape
{
Area: 70
Abstract Class
inherit Runtime virtual
method Function Runtime virtual method
program
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);
}
}
class Tester
{
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
// 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);
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
Console.ReadKey();
}
}
}
Operator Description
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;
}
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;
// 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
interface Display {
void Print(); // method name no method body
}
class finalDisplay : Display
{
public void Print()
{
Console.WriteLine("Base Display"); // method body
}
}
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);
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900
NameSpaces
Class (or)
InterFace
Method (or)
Function
Statement
Namespace firsthouse
{
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
{
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
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()
{
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();
}
}
Inside first_space
Inside second_space
Nested Namespaces
Namesapce namespace nested namespace
NameSpaces
First
Namesapce
Second
Method (or)
Function
Statement
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
#define TestMode
Using System ;
Namespace testname
{
Class test
{
}
}
#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
Syntex S
Operator symb preprocessor
#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!
Character Escapes
\r\n(\w+) \r\nHello in
\n New Line (\u000A)
\r\nHello\nWorld
\e \u001B (Escape) \e \x001B in \x001B
\ Octal value 3 Digit
Character Classes
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
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
\b
boundary ends,ender,ends in
Grouping Constructs
)*(?(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
( )
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
*? ? 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>
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
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
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
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
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);
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();
}
}
}
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();
}
}
}
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
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
}
Handling Exceptions
using System;
namespace dividingByZero
{
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();
}
}
}
using System;
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);
}
}
}
Throwing
Objects
System.Exception class drived ( ) object
catch block Throw ( ) Throw statement Throw
( )
using System;
namespace Throw_statement
{
class Program
{
static void Main(string[] args)
{
int num1, num2, result;
try
{
try
{
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
}
catch (DivideByZeroException e)
{
throw;
}
}
catch (Exception e)
{
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
StreamReader
Byte Byte
BinaryReader Gzip Stream IsolatedStorag
e Stream
BinaryWriter Crypto Stream
MemoryStream
Network Stream
Xmlwriter
StringReader
StringWriter
C# I/O Classes
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
Filestream object F
file .x file mode FileAccess File read
FileShare read write
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 ()
using System;
using System.IO;
namespace FileIOApplication
{
class Program
{
static void Main(string[] args)
{
FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate,
FileAccess.ReadWrite);
F.Position = 0;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
StreamReader Class
StreamReader class TextReader class inheritance text reader
StreamReader member method
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"))
{
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
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();
}
}
}
Zara Ali
Nuha Ali
using System;
using System.IO;
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();
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
6 LastAccessTime
File ( ) Directory Time
7 Name
Directory name
DirectoryInfo method
8 Directory
file Directory
9 LastWriteTime
File write
10 Length
File size
FileInfo method
using System;
using System.IO;
namespace WindowsFileApplication
{
class Program
{
static void Main(string[] args)
{
//creating a DirectoryInfo object
DirectoryInfo mydir = new DirectoryInfo(@"c:\Windows");
System Information ( )
class, constructor, delegate, enum, event, field, interface, method, portable executable file module,
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(
validon, AllowMultiple=allowmultiple,
Inherited=inherited
)]
[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;
}
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();
}
}
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
)]
using System;
public class MyClass
{
[Obsolete("Don't use OldMethod, use NewMethod instead", true)]
static void OldMethod()
{
Console.WriteLine("It is the old method");
}
static void NewMethod()
{
Console.WriteLine("It is the new method");
}
public static void Main()
{
OldMethod();
}
}
Custom Attributes
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
[AttributeUsage(AttributeTargets.All)]
HelpAttribute
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
{
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);
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:
set
{
name = value;
}
}
// Declare a Age property of type int
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
using System;
class Student
{
Abstract Properties
using System;
public abstract class Person
{
public abstract string Name
{
get;
set;
}
public abstract int Age
{
get;
set;
}
}
class Student : Person
{
{
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();
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;
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";
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
Overloaded Indexers
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.";
}
}
public string this[int index]
{
get
{
string tmp;
}
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";
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
Declaring Delegates
Instantiating Delegates
using System;
alue of Num: 35
Value of Num: 175
Multicasting of a Delegates
using System;
Value of Num: 75
Use of Delegates
using System;
using System.IO;
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// delegate declaration
public delegate void printString(string s);
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();
}
}
}
Declaring Events
Events Events Delegate
event keyword Events create
Keyword: event
Event event-delegate object-name
Event-delegate: delegate name
Object-name: event name
using System;
namespace SimpleEvent
{
using System;
Event Fired!
Event Fired!
Event Fired!
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;
}
}//end of main
}//end of RecordBoilerInfo
}
Logging info:
Temperature 100
Pressure 12
Message: O. K
( ) Data
Class Collection Class Stacks Queues List
Hash Table Collection Class
Collection Class Data
Class
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
Source ArrayList
ArrayList
using System;
using System.Collections;
namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{
Hashtable
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");
SortedList
Property Description
SortedList / Get,Set
Capacity
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");
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
Stack
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
{
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
Queue
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");
q.Enqueue(".");
q.Enqueue("Aung");
q.Enqueue("Ko");
Console.WriteLine("Current queue: ");
Console.WriteLine();
q.Enqueue("Min");
q.Enqueue("Thu");
Current queue:
Dr.Aung Ko
Current queue:
Dr.Aung Ko Min Thu
Removing some values
The removed value:Dr
The removed value:.
BitArray
Property Description
Count BitArray bit Get
BitArray
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
//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();
}
}
}
using System;
{
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
Pointer Variables
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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
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();
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();
}
}
}
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
)
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
3 public void Interrupt() Interrupts a thread that is in the WaitSleepJoin thread state.
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();
}
}
}
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();
}
}
}
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();
Console.ReadKey();
}
}
}
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
}
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 { }
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
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();
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();
}
}
}
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
Byte keyword
byte myByte = 255;
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
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);
}
}
}
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
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
{
// 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();
}
}
}
al Studio 2012\Projects\checkedeg\checkedeg\Program.cs:line 21
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 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);
}
}
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();
}
}
Const
C L C K
C
C initialized
initialized C -
-
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
12.1
My amount = $1.00
Your amount = $9,999,999,999,999,999,999,999,999,999.00
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);
class DelegateTest
{
// Regular method that matches signature:
static double Double(double input)
{
return input * 2;
}
multByTwo: 9
square: 25
cube: 83.740234375
Do
Do statement Condition block statement(s)
C block
0
1
2
3
4
Double
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);
}
}
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.");
}
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 };
Sun = 0
Fri = 5
Event
Events user mouse Click ( ) mouse wheel user
user mouse E
key C Event Event
class member Eevnt Keyword event
Event Event
.Explicit
Explicit Type Convertion C# pre-defined
Functions( .C . S ) )
Explicit Type Convertion
Explicit Conversion operator Conversion operator
Ex
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()
{
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);
False
F )
false Operator a != b)
false Literal bool a = false;)
Finally
Finally keyword try block Exception Handle
Error
finally block finally block statements
Exception Handling
try
{
// Invalid conversion; obj contains a string, not a numeric type.
i = (int)obj;
}
}
Fixed
Fixed keyword garbage collector variable
Fiexed keyword unsafe code Buffers size x
Fiexed keyword
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
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());
}
}
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
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);
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.");
If
If statement Boolean value execute Boolean
variable result if block statement
if (result)
{
Console.WriteLine("The variable is set to true.");
}
else
{
Console.WriteLine("The variable is set to false.");
}
Implicit
I
I
class Digit
{
public Digit(double d) { val = d; }
public double val;
// ...other members
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
{
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> { }
class Program
{
static void Test()
{
IContravariant<Object> iobj = new Sample<Object>();
IContravariant<String> istr = new Sample<String>();
Int
Int keyword integral type
range
Int
int i = 123;
Int
// '123' is an int, so an implicit conversion takes place here:
float f = 123;
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)
{
_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
// 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."
}
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();
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 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:
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
//using System.Threading;
class ThreadTest
{
public void RunMe()
{
Console.WriteLine("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
)
L )
)
x
Namespace
Namespace keyword Object
namespace SampleNamespace
{
class SampleClass { }
interface SampleInterface { }
struct SampleStruct { }
enum SampleEnum { a, b }
namespace SampleNamespace.Nested
{
class SampleClass2 { }
}
}
another namespace
class
interface
struct
enum
delegate
namespace SomeNameSpace
{
public class MyClass
{
static void Main()
{
Nested.NestedNameSpaceClass.SayHello();
}
}
// 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() { }
}
// Returns true.
Console.WriteLine("null == null is {0}", null == null);
}
}
Object
Object type NET.Framework Object C#
predefined type user-defined type reference type value type object
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));
}
}
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
}
}
// Covariant interface.
interface ICovariant<out 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
}
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();
}
}
class TestOverride
{
public class Employee
{
public string name;
Params
Params keyword arguments
arguments pass argument
,
{
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[]
Private
Private keyword access modifier Private
variable class private
variable class
class Employee2
{
private string name = "FirstName, LastName";
private double salary = 100.0;
Protected
Protected keyword access modifier Protected
variable class class derived class
class A
{
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
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);
}
}
Ref
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()
{
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();
}
}
Sbyte
Sbyte keyword integral type
range
Type Range Size .NET Framework type
sbyte -128 to 127 Signed 8-bit integer System. SByte
Sbyte
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
{
// 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 x = 5, y = 12;
Sizeof
Data type Data size Sizeof keyword
Sizeof operator overloading Sizeof return
Expression Constant value
sizeof(sbyte) 1
sizeof(byte) 1
sizeof(short) 2
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));
}
}
Stackalloc
Stackalloc keyword unsafe code (unsafe code security
) Stackalloc keyword variable
memory
int* 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
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;
}
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; }
}
}
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();
}
}
Throw
Program execute error Exeception
throw statement Throw singnal
Throw object system.Exception
derive
}
}
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)
{
}
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#
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);
}
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
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();
}
}
try
{
ProcessString(s);
}
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();
}
}
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.
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);
}
}
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");
try
{
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);
}
}
}
// 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
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.
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.
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()
{
}
{
Console.Write("Enter the employee's name: ");
string name = Console.ReadLine();
Console.Write("Enter the employee's ID: ");
string id = Console.ReadLine();
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;
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.
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";
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"
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
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.
Switch
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
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");
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");
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 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
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() {}
Console.WriteLine("Methods:");
System.Reflection.MethodInfo[] methodInfo = t.GetMethods();
Console.WriteLine("Members:");
System.Reflection.MemberInfo[] memberInfo = t.GetMembers();
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;
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).
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) {}
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 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
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
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
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.
}
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;
}
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
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
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
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.
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; }
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.
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
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).
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.
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
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;
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
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.
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);
}