Spec. Most of the statements in C # are borrowed directly from C and C + +, but there are some noteworthy additions and modifications. The following table lists the available statement types and provides examples for each type.
Statement Example
Statement list and block statement static void Main () {
F ();
G ();
{
H ();
I ();
}
}
Tag statement and goto statement static void Main (string[] args) {
if (args. Length = = 0)
Goto done;
Console.WriteLine (args. Length);
Done
Console.WriteLine ("Done");
}
Local constant declaration static void Main () {
const float PI = 3.14f;
const int r = 123;
Console.WriteLine (PI * R * r);
}
local variable declaration static void Main () {
int A;
int B = 2, c = 3;
A = 1;
Console.WriteLine (A + B + c);
}
expression statement static int F (int a, int b) {
return a + B;
}
static void Main () {
F (1, 2); Expression statement
}
If statement static void Main (string[] args) {
if (args. Length = = 0)
Console.WriteLine ("No args");
Else
Console.WriteLine ("Args");
}
switch statement static void Main (string[] args) {
switch (args. Length) {
case 0:
Console.WriteLine ("No args");
break;
Case 1:
Console.WriteLine ("One Arg");
break;
Default:
int n = args. Length;
Console.WriteLine ("{0} args", n);
break;
}
}
While statement static void Main (string[] args) {
int i = 0;
while (I < args. Length) {
Console.WriteLine (Args[i]);
i++;
}
}
Do statement static void Main () {
string S;
do {s = Console.ReadLine ();}
while (S!= "Exit");
}
For statement static void Main (string[] args) {
for (int i = 0; i < args. Length; i++)
Console.WriteLine (Args[i]);
}
foreach statement static void Main (string[] args) {
foreach (string s in args)
Console.WriteLine (s);
}
Break statement static void Main (string[] args) {
int i = 0;
while (true) {
if (i = = args. Length)
Break
Console.WriteLine (args[i++]);
}
}
Continue statement static void Main (string[] args) {
int i = 0;
while (true) {
Console.WriteLine (args[i++]);
if (i < args. Length)
Continue
Break
}
}
Return statement static int F (int a, int b) {
return a + B;
}
static void Main () {
Console.WriteLine (F (1, 2));
Return
}
Throw statement and try statement static int F (int a, int b) {
if (b = = 0)
throw new Exception ("Divide by Zero");
return a/b;
}
static void Main () {
try {
Console.WriteLine (F (5, 0));
}
catch (Exception e) {
Console.WriteLine ("Error");
}
}
Checked and unchecked statements static void Main () {
int x = Int32.MaxValue;
Console.WriteLine (x + 1); Overflow
Checked {
Console.WriteLine (x + 1); Exception
}
Unchecked {
Console.WriteLine (x + 1); Overflow
}
}
lock statement static void Main () {
A A = ...;
Lock (a) {
A.P = A.P + 1;
}
}
Using statement static void Main () {
using (Resource r = new Resource ()) {
R.F ();
}
}