Sie sind auf Seite 1von 80

C# Control Statement

C# If Example

1. using System;
2. public class IfExample
3. {
4. public static void Main(string[] args)
5. {
6. int num = 10;
7. if (num % 2 == 0)
8. {
9. Console.WriteLine("It is even number");
10. }
11.
12. }
13. }

Output:
It is even number

C# If-else Example

1. using System;
2. public class IfExample
3. {
4. public static void Main(string[] args)
5. {
6. int num = 11;
7. if (num % 2 == 0)
8. {
9. Console.WriteLine("It is even number");
10. }
11. else
12. {
13. Console.WriteLine("It is odd number");
14. }
15.
16. }
17. }

Output:

It is odd number

C# If-else Example: with input from user


1. sing System;
2. public class IfExample
3. {
4. public static void Main(string[] args)
5. {
6. Console.WriteLine("Enter a number:");
7. int num = Convert.ToInt32(Console.ReadLine());
8.
9. if (num % 2 == 0)
10. {
11. Console.WriteLine("It is even number");
12. }
13. else
14. {
15. Console.WriteLine("It is odd number");
16. }
17.
18. }
19. }

Output:

Enter a number:11
It is odd number

Output:

Enter a number:12
It is even number

C# IF-else-if ladder Statement


C# If else-if Example
1. using System;
2. public class IfExample
3. {
4. public static void Main(string[] args)
5. {
6. Console.WriteLine("Enter a number to check grade:");
7. int num = Convert.ToInt32(Console.ReadLine());
8.
9. if (num <0 || num >100)
10. {
11. Console.WriteLine("wrong number");
12. }
13. else if(num >= 0 && num < 50){
14. Console.WriteLine("Fail");
15. }
16. else if (num >= 50 && num < 60)
17. {
18. Console.WriteLine("D Grade");
19. }
20. else if (num >= 60 && num < 70)
21. {
22. Console.WriteLine("C Grade");
23. }
24. else if (num >= 70 && num < 80)
25. {
26. Console.WriteLine("B Grade");
27. }
28. else if (num >= 80 && num < 90)
29. {
30. Console.WriteLine("A Grade");
31. }
32. else if (num >= 90 && num <= 100)
33. {
34. Console.WriteLine("A+ Grade");
35. }
36. }
37. }
Output:

Enter a number to check grade:66


C Grade

Output:

Enter a number to check grade:-2


wrong number

C# switch
C# Switch Example

1. using System;
2. public class SwitchExample
3. {
4. public static void Main(string[] args)
5. {
6. Console.WriteLine("Enter a number:");
7. int num = Convert.ToInt32(Console.ReadLine());
8.
9. switch (num)
10. {
11. case 10: Console.WriteLine("It is 10"); break;
12. case 20: Console.WriteLine("It is 20"); break;
13. case 30: Console.WriteLine("It is 30"); break;
14. default: Console.WriteLine("Not 10, 20 or 30"); break;
15. }
16. }
17. }

Output:

Enter a number:
10
It is 10

Output:

Enter a number:
55
Not 10, 20 or 30
using System;
public class Program

public static void Main()

int x = 10;

switch (x)

case 5:

Console.WriteLine("Value of x is 5");

break;

case 10:

Console.WriteLine("Value of x is 10");

break;

case 15:

Console.WriteLine("Value of x is 15");

break;

default:

Console.WriteLine("Unknown value");

break;

}
value of x is 10

Nested switch:
xample: Nested switch statements
using System;

public class Program


{
public static void Main()
{
int j = 5;

switch (j)
{
int j = 5;

switch (j)
{
case 5:
Console.WriteLine(5);
switch (j - 1)
{
case 4:
Console.WriteLine(4);
switch (j - 2)
{
case 3:
Console.WriteLine(3);
break;
}
break;
}
break;
case 10:
Console.WriteLine(10);
break;
case 15:
Console.WriteLine(15);
break;
default:
Console.WriteLine(100);
break;
}
}
}
5
4
3
C# program that uses switch, ToLower

using System;

class Program
{
static void Main()
{
Console.WriteLine(IsDogCaseInsensitive("WHIPPET"));
Console.WriteLine(IsDogCaseInsensitive("sphynx"));
}

static bool IsDogCaseInsensitive(string value)


{
switch (value.ToLower())
{
case "irish terrier":
case "jagdterrier":
case "keeshond":
case "sulimov dog":
case "whippet":
case "eurasier":
case "brittany":
return true;
default:
return false;
}
}
}

Output

True
False

C# program that benchmarks string switch

using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
string[] trees = new string[] { "Adler", "Persimmon",
"???" };
int treeCount = 0;
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
foreach (string tree in trees)
{
if (IsTree(tree))
{
treeCount++;
}
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
foreach (string tree in trees)
{
if (IsTreeExpression(tree))
{
treeCount++;
}
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds
* 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds
* 1000000) /
_max).ToString("0.00 ns"));
Console.Read();
}

static bool IsTree(string value)


{
switch (value)
{
case "Alder":
case "Elderberry":
case "Chestnut":
case "Guava":
case "Willow":
case "Elm":
case "Persimmon":
return true;
default:
return false;
}
}

static bool IsTreeExpression(string value)


{
return (value == "Alder" ||
value == "Elderberry" ||
value == "Chestnut" ||
value == "Guava" ||
value == "Willow" ||
value == "Elm" ||
value == "Persimmon");
}
}

Results

32.94 ns switch (IsTree)


78.21 ns if (IsTreeExpression)

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
int val = 5;
switch (val)
{
case 1:
MessageBox.Show("The day is - Sunday");
break;
case 2:
MessageBox.Show("The day is - Monday");
break;
case 3:
MessageBox.Show("The day is - Tuesday");
break;
case 4:
MessageBox.Show("The day is - wednesday");
break;
case 5:
MessageBox.Show("The day is - Thursday");
break;
case 6:
MessageBox.Show("The day is - Friday");
break;
case 7:
MessageBox.Show("The day is - Saturday");
break;
default:
MessageBox.Show("Out of range !!");
break;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
findStatus("A+");
}
public void findStatus(string val)
{
switch (val)
{
case "A+":
MessageBox.Show("Excellent !!");
break;
case "A":
MessageBox.Show("Very Good !!");
break;
case "B":
MessageBox.Show("Good !!");
break;
case "C":
MessageBox.Show("Passed !!");
break;
case "D":
MessageBox.Show("Failed !!");
break;
default:
MessageBox.Show("Out of range !!");
break;
}
}
}
}
C# For Loop
C# For Loop Example

1. using System;
2. public class ForExample
3. {
4. public static void Main(string[] args)
5. {
6. for(int i=1;i<=10;i++){
7. Console.WriteLine(i);
8. }
9. }
10. }

Output:

1
2
3
4
5
6
7
8
9
10

C# Nested For Loop


1. using System;
2. public class ForExample
3. {
4. public static void Main(string[] args)
5. {
6. for(int i=1;i<=3;i++){
7. for(int j=1;j<=3;j++){
8. Console.WriteLine(i+" "+j);
9. }
10. }
11. }
12. }
Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C# Infinite For Loop


1. sing System;
2. public class ForExample
3. {
4. public static void Main(string[] args)
5. {
6. for (; ;)
7. {
8. Console.WriteLine("Infinitive For Loop");
9. }
10. }
11. }

Output:

Infinitive For Loop


Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c
example: break in for loop
using System;

public class Program


{
public static void Main()
{
for (int i = 0; i < 10; i++)
{
if( i == 5 )
break;

Console.WriteLine("Value of i: {0}", i);


}

}
}
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4

C# While Loop
C# While Loop Example

1. using System;
2. public class WhileExample
3. {
4. public static void Main(string[] args)
5. {
6. int i=1;
7. while(i<=10)
8. {
9. Console.WriteLine(i);
10. i++;
11. }
12. }
13. }

Output:

1
2
3
4
5
6
7
8
9
10

C# Nested While Loop Example:

1. using System;
2. public class WhileExample
3. {
4. public static void Main(string[] args)
5. {
6. int i=1;
7. while(i<=3)
8. {
9. int j = 1;
10. while (j <= 3)
11. {
12. Console.WriteLine(i+" "+j);
13. j++;
14. }
15. i++;
16. }
17. }
18. }

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C# Infinitive While Loop Example:

1. sing System;
2. public class WhileExample
3. {
4. public static void Main(string[] args)
5. {
6. while(true)
7. {
8. Console.WriteLine("Infinitive While Loop");
9. }
10. }
11. }
Output:

Infinitive While Loop


Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c
Example: break in while loop
using System;

public class Program


{
public static void Main()
{
int i = 0;

while (true)
{
Console.WriteLine("Value of i: {0}", i);

i++;

if (i > 10)
break;
}
}
}
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
Value of i: 10

C# - do while
C# do-while Loop Example

1. using System;
2. public class DoWhileExample
3. {
4. public static void Main(string[] args)
5. {
6. int i = 1;
7.
8. do{
9. Console.WriteLine(i);
10. i++;
11. } while (i <= 10) ;
12.
13. }
14. }
15. Output:
16. 1
17. 2
18. 3
19. 4
20. 5
21. 6
22. 7
23. 8
24. 9
25. 10

C# Nested do-while Loop


1. using System;
2. public class DoWhileExample
3. {
4. public static void Main(string[] args)
5. {
6. int i=1;
7.
8. do{
9. int j = 1;
10.
11. do{
12. Console.WriteLine(i+" "+j);
13. j++;
14. } while (j <= 3) ;
15. i++;
16. } while (i <= 3) ;
17. }
18. }

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C# Infinitive do-wh ile Loop


C# Infinitive do-while Loop Example

1. using System;
2. public class WhileExample
3. {
4. public static void Main(string[] args)
5. {
6.
7. do{
8. Console.WriteLine("Infinitive do-while Loop");
9. } while(true);
10. }
11. }

Output:

Infinitive do-while Loop


Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c
C# Loop Programming Examples
Write a program to display table of given number.

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace Loop_Examples1
7. {
8. class Program
9. {
10. static void Main(string[] args)
11. {
12. int num, i, result;
13. Console.Write("Enter a number\t");
14. num = Convert.ToInt32(Console.ReadLine());
15.
16. for (i = 1; i <= 10; i++)
17. {
18. result = num * i;
19. Console.WriteLine("{0} x {1} = {2}", num, i, result);
20. }
21. Console.ReadLine();
22. }
23. }
24. }

Output
Enter a number 8

8 x 1 = 8

8 x 2 = 16

8 x 3 = 24

8 x 4 = 32

8 x 5 = 40

8 x 6 = 48

8 x 7 = 56

8 x 8 = 64

8 x 9 = 72

8 x 10 = 80

__
Write a program to print following output using for loop. 1
22
333
4444
55555

Answer:

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace Loop_Example2
7. {
8. class Program
9. {
10. static void Main(string[] args)
11. {
12. int i, j;
13. i = 0;
14. j = 0;
15.
16. for (i = 1; i <= 5; i++)
17. {
18. for (j = 1; j <= i; j++)
19. {
20. Console.Write(i);
21. }
22. Console.Write("\n");
23. }
24. Console.ReadLine();
25. }
26. }
27. }

Output
1

22

333

4444

55555
__

Example: break inside do-while


using System;

public class Program


{
public static void Main()
{
int i = 0;

do
{
Console.WriteLine("Value of i: {0}", i);

i++;

if (i > 5)
break;

} while (true);
}
}
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
C# Break Statement
C# Break Statement Example

1. using System;
2. public class BreakExample
3. {
4. public static void Main(string[] args)
5. {
6. for (int i = 1; i <= 10; i++)
7. {
8. if (i == 5)
9. {
10. break;
11. }
12. Console.WriteLine(i);
13. }
14. }
15. }

Output:

1
2
3
4

C# Break Statement with Inner Loop

1. using System;
2. public class BreakExample
3. {
4. public static void Main(string[] args)
5. {
6. for(int i=1;i<=3;i++){
7. for(int j=1;j<=3;j++){
8. if(i==2&&j==2){
9. break;
10. }
11. Console.WriteLine(i+" "+j);
12. }
13. }
14. }
15. }

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

C# Continue Statement
C# Continue Statement Example

1. using System;
2. public class ContinueExample
3. {
4. public static void Main(string[] args)
5. {
6. for(int i=1;i<=10;i++){
7. if(i==5){
8. continue;
9. }
10. Console.WriteLine(i);
11. }
12. }
13. }

Output:

1
2
3
4
6
7
8
9
1
C# Continue Statement with Inner Loop

1. using System;
2. public class ContinueExample
3. {
4. public static void Main(string[] args)
5. {
6. for(int i=1;i<=3;i++){
7. for(int j=1;j<=3;j++){
8. if(i==2&&j==2){
9. continue;
10. }
11. Console.WriteLine(i+" "+j);
12. }
13. }
14. }
15. }

Output:

1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

C# Goto Statement
C# Goto Statement Example

1. using System;
2. public class GotoExample
3. {
4. public static void Main(string[] args)
5. {
6. ineligible:
7. Console.WriteLine("You are not eligible to vote!");
8.
9. Console.WriteLine("Enter your age:\n");
10. int age = Convert.ToInt32(Console.ReadLine());
11. if (age < 18){
12. goto ineligible;
13. }
14. else
15. {
16. Console.WriteLine("You are eligible to vote!");
17. }
18. }
19. }

Output:

You are not eligible to vote!


Enter your age:
11
You are not eligible to vote!
Enter your age:
5
You are not eligible to vote!
Enter your age:
26
You are eligible to vote!

C# Comments
C# Single Line Comment

1. using System;
2. public class CommentExample
3. {
4. public static void Main(string[] args)
5. {
6. int x = 10;//Here, x is a variable
7. Console.WriteLine(x);
8. }
9. }

Output:
10

C# Multi Line Comment

1. using System;
2. public class CommentExample
3. {
4. public static void Main(string[] args)
5. {
6. /* Let's declare and
7. print variable in C#. */
8. int x=20;
9. Console.WriteLine(x);
10. }
11. }

Output:

20

C# Function
C# Function: using no parameter and return type

1. using System;
2. namespace FunctionExample
3. {
4. class Program
5. {
6. // User defined function without return type
7. public void Show() // No Parameter
8. {
9. Console.WriteLine("This is non parameterized function");
10. // No return statement
11. }
12. // Main function, execution entry point of the program
13. static void Main(string[] args)
14. {
15. Program program = new Program(); // Creating Object
16. program.Show(); // Calling Function
17. }
18. }
19. }

Output:

This is non parameterized function

C# Function: using parameter but no return type

1. using System;

2. using System;
3. namespace FunctionExample
4. {
5. class Program
6. {
7. // User defined function without return type
8. public void Show(string message)
9. {
10. Console.WriteLine("Hello " + message);
11. // No return statement
12. }
13. // Main function, execution entry point of the program
14. static void Main(string[] args)
15. {
16. Program program = new Program(); // Creating Object
17. program.Show("Rahul Kumar"); // Calling Function
18. }
19. }
20. }

Output:

Hello Rahul Kumar


C# Function: using parameter and return type

1. using System;
2. namespace FunctionExample
3. {
4. class Program
5. {
6. // User defined function
7. public string Show(string message)
8. {
9. Console.WriteLine("Inside Show Function");
10. return message;
11. }
12. // Main function, execution entry point of the program
13. static void Main(string[] args)
14. {
15. Program program = new Program();
16. string message = program.Show("Rahul Kumar");
17. Console.WriteLine("Hello "+message);
18. }
19. }
20. }

Output:

Inside Show Function


Hello Rahul Kumar

C# Call By Value
C# Call By Value Example

1. using System;
2. namespace CallByValue
3. {
4. class Program
5. {
6. // User defined function
7. public void Show(int val)
8. {
9. val *= val; // Manipulating value
10. Console.WriteLine("Value inside the show function "+val);
11. // No return statement
12. }
13. // Main function, execution entry point of the program
14. static void Main(string[] args)
15. {
16. int val = 50;
17. Program program = new Program(); // Creating Object
18. Console.WriteLine("Value before calling the function "+val);
19. program.Show(val); // Calling Function by passing value
20. Console.WriteLine("Value after calling the function " + val);
21. }
22. }
23. }

Output:

Value before calling the function 50


Value inside the show function 2500
Value after calling the function 50

C# Call By Reference
C# Call By Reference Example

1. using System;
2. namespace CallByReference
3. {
4. class Program
5. {
6. // User defined function
7. public void Show(ref int val)
8. {
9. val *= val; // Manipulating value
10. Console.WriteLine("Value inside the show function "+val);
11. // No return statement
12. }
13. // Main function, execution entry point of the program
14. static void Main(string[] args)
15. {
16. int val = 50;
17. Program program = new Program(); // Creating Object
18. Console.WriteLine("Value before calling the function "+val);
19. program.Show(ref val); // Calling Function by passing reference
20. Console.WriteLine("Value after calling the function " + val);
21. }
22. }
23. }

Output:

Value before calling the function 50


Value inside the show function 2500
Value after calling the function 2500

C# Out Parameter
C# Out Parameter Example 1

1. using System;
2. namespace OutParameter
3. {
4. class Program
5. {
6. // User defined function
7. public void Show(out int val) // Out parameter
8. {
9. int square = 5;
10. val = square;
11. val *= val; // Manipulating value
12. }
13. // Main function, execution entry point of the program
14. static void Main(string[] args)
15. {
16. int val = 50;
17. Program program = new Program(); // Creating Object
18. Console.WriteLine("Value before passing out variable " + val);
19. program.Show(out val); // Passing out argument
20. Console.WriteLine("Value after recieving the out variable " + val);
21. }
22. }
23. }

Output:

Value before passing out variable 50


Value after receiving the out variable 25

C# Out Parameter Example 2

1. using System;
2. namespace OutParameter
3. {
4. class Program
5. {
6. // User defined function
7. public void Show(out int a, out int b) // Out parameter
8. {
9. int square = 5;
10. a = square;
11. b = square;
12. // Manipulating value
13. a *= a;
14. b *= b;
15. }
16. // Main function, execution entry point of the program
17. static void Main(string[] args)
18. {
19. int val1 = 50, val2 = 100;
20. Program program = new Program(); // Creating Object
21. Console.WriteLine("Value before passing \n val1 = " + val1+" \n val2 = "+val2);
22. program.Show(out val1, out val2); // Passing out argument
23. Console.WriteLine("Value after passing \n val1 = " + val1 + " \n val2 = " + val2);
24. }
25. }
26. }

Output:

Value before passing


val1 = 50
val2 = 100
Value after passing
val1 = 25
val2 = 25

C# Arrays
1. using System;
2. public class ArrayExample
3. {
4. public static void Main(string[] args)
5. {
6. int[] arr = new int[5];//creating array
7. arr[0] = 10;//initializing array
8. arr[2] = 20;
9. arr[4] = 30;
10.
11. //traversing array
12. for (int i = 0; i < arr.Length; i++)
13. {
14. Console.WriteLine(arr[i]);
15. }
16. }
17. }

Output:

10
0
20
0
30

C# Array Example: Declaration and Initialization at same time


1. using System;
2. public class ArrayExample
3. {
4. public static void Main(string[] args)
5. {
6. int[] arr = { 10, 20, 30, 40, 50 };//Declaration and Initialization of array
7.
8. //traversing array
9. for (int i = 0; i < arr.Length; i++)
10. {
11. Console.WriteLine(arr[i]);
12. }
13. }
14. }

Output:

10
20
30
40
50

C# Array Example: Traversal using foreach loop

1. using System;
2. public class ArrayExample
3. {
4. public static void Main(string[] args)
5. {
6. int[] arr = { 10, 20, 30, 40, 50 };//creating and initializing array
7.
8. //traversing array
9. foreach (int i in arr)
10. {
11. Console.WriteLine(i);
12. }
13. }
14. }
Output:

10
20
30
40
50

C# Passing Array to Function


C# Passing Array to Function Example: print array elements

1. using System;
2. public class ArrayExample
3. {
4. static void printArray(int[] arr)
5. {
6. Console.WriteLine("Printing array elements:");
7. for (int i = 0; i < arr.Length; i++)
8. {
9. Console.WriteLine(arr[i]);
10. }
11. }
12. public static void Main(string[] args)
13. {
14. int[] arr1 = { 25, 10, 20, 15, 40, 50 };
15. int[] arr2 = { 12, 23, 44, 11, 54 };
16. printArray(arr1);//passing array to function
17. printArray(arr2);
18. }
19. }

Output:

Printing array elements:


25
10
20
15
40
50
Printing array elements:
12
23
44
11
54

C# Passing Array to Function Example: Print minimum number

1. using System;
2. public class ArrayExample
3. {
4. static void printMin(int[] arr)
5. {
6. int min = arr[0];
7. for (int i = 1; i < arr.Length; i++)
8. {
9. if (min > arr[i])
10. {
11. min = arr[i];
12. }
13. }
14. Console.WriteLine("Minimum element is: " + min);
15. }
16. public static void Main(string[] args)
17. {
18. int[] arr1 = { 25, 10, 20, 15, 40, 50 };
19. int[] arr2 = { 12, 23, 44, 11, 54 };
20.
21. printMin(arr1);//passing array to function
22. printMin(arr2);
23. }
24. }

Output:

Minimum element is: 10


Minimum element is: 11

C# Passing Array to Function Example: Print maximum number

1. using System;
2. public class ArrayExample
3. {
4. static void printMax(int[] arr)
5. {
6. int max = arr[0];
7. for (int i = 1; i < arr.Length; i++)
8. {
9. if (max < arr[i])
10. {
11. max = arr[i];
12. }
13. }
14. Console.WriteLine("Maximum element is: " + max);
15. }
16. public static void Main(string[] args)
17. {
18. int[] arr1 = { 25, 10, 20, 15, 40, 50 };
19. int[] arr2 = { 12, 23, 64, 11, 54 };
20.
21. printMax(arr1);//passing array to function
22. printMax(arr2);
23. }
24. }

Output:

Maximum element is: 50


Maximum element is: 64
Write A Program To Print One Dimensional Array In Reverse
Order
1. sing System;
2.
3. namespace Sort_Array_Des
4. {
5. public class Program
6. {
7. public static void Main(string[] args)
8. {
9. int[] num= {22,50,11, 2, 49};
10. Array.Reverse(num);
11. for(int i=0; i<num.Length; i++)
12. {
13. Console.Write(num[i] + " ");
14. }
15. }
16. }
17. }
18.

Output
49 2 11 50 22 _
Write A Program To Sort One Dimensional Array In Descending
Order Using Non Static Method
1. ng System;
2.
3. namespace Sort_Array_Des
4. {
5. public class Program
6. {
7. public static void Main(string[] args)
8. {
9. int[] num= {22,50,11, 2, 49};
10. Program p=new Program();
11. p.SortArray(num);
12. }
13.
14. public void SortArray(int[] numarray)
15. {
16. int swap = 0;
17. for(int i=0; i<numarray.Length; i++)
18. {
19. for(int j=i+1; j<numarray.Length; j++)
20. {
21. if(numarray[i]<=numarray[j])
22. {
23. swap=numarray[j];
24. numarray[j]=numarray[i];
25. numarray[i]=swap;
26. }
27. }
28. Console.Write(numarray[i] + " ");
29. }
30. }
31. }
32. }
33.

output
50 49 22 11 2 _
Write A Program To Sort One Dimensional Array In Desending
Order Static Class Array Method
1. using System;
2.
3. namespace Sort_Array_Des
4. {
5. public class Program
6. {
7. public static void Main(string[] args)
8. {
9. int[] num= {22,50,11, 2, 49};
10. Array.Sort(num);
11. Array.Reverse(num);
12. for(int i=0; i<num.Length; i++)
13. {
14. Console.Write(num[i] + " ");
15. }
16. }
17. }
18. }

Output
50 49 22 11 2 _

C# Multidimensional Arrays
C# Multidimensional Array Example

1. using System;
2. public class MultiArrayExample
3. {
4. public static void Main(string[] args)
5. {
6. int[,] arr=new int[3,3];//declaration of 2D array
7. arr[0,1]=10;//initialization
8. arr[1,2]=20;
9. arr[2,0]=30;
10.
11. //traversal
12. for(int i=0;i<3;i++){
13. for(int j=0;j<3;j++){
14. Console.Write(arr[i,j]+" ");
15. }
16. Console.WriteLine();//new line at each row
17. }
18. }
19. }

Output:

0 10 0
0 0 20
30 0 0

C# Multidimensional A rray Example: Declaration and


initialization at same time

1. using System;
2. public class MultiArrayExample
3. {
4. public static void Main(string[] args)
5. {
6. int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//declaration and initialization
7.
8. //traversal
9. for(int i=0;i<3;i++){
10. for(int j=0;j<3;j++){
11. Console.Write(arr[i,j]+" ");
12. }
13. Console.WriteLine();//new line at each row
14. }
15. }
16. }

Output:

1 2 3
4 5 6
7 8 9
Write A Program To Add The Diagonal Of Two-Dimensional
Array
Programming Example

1. using System;
2.
3. namespace Add_Diagonal
4. {
5. public class Program
6. {
7. public static void Main(string[] args)
8. {
9. int[,] num= {
10. {22,50,11, 2, 49},
11. {92,63,12,64,37},
12. {75,23,64,12,99},
13. {21,25,71,69,39},
14. {19,39,58,28,83}};
15.
16. //Getting Row and Column Length
17. int rowlength = num.GetLength(0);
18. int columnlength = num.GetLength(1);
19. int total=0;
20. Console.Write("Diagonals are : ");
21. for(int row=0; row<rowlength; row++)
22. {
23. for(int column=0; column<columnlength; column++)
24. {
25. if(row==column)
26. {
27. Console.Write(num[row,column] + " ");
28. total += num[row,column];
29. }
30. }
31. }
32. Console.WriteLine(": Sum : " + total);
33. }
34. }
35. }

Output
Diagonals are : 22 63 64 69 83 : Sum : 301 _

C# Jagged Arrays
C# Jagged Array Example
1. public class JaggedArrayTest
2. {
3. public static void Main()
4. {
5. int[][] arr = new int[2][];// Declare the array
6.
7. arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
8. arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
9.
10. // Traverse array elements
11. for (int i = 0; i < arr.Length; i++)
12. {
13. for (int j = 0; j < arr[i].Length; j++)
14. {
15. System.Console.Write(arr[i][j]+" ");
16. }
17. System.Console.WriteLine();
18. }
19. }
20. }

Output:

11 21 56 78
42 61 37 41 59 63

Initialization of Jagged array upon Declaration

C# Jagged Array Example 2

1. public class JaggedArrayTest


2. {
3. public static void Main()
4. {
5. int[][] arr = new int[3][]{
6. new int[] { 11, 21, 56, 78 },
7. new int[] { 2, 5, 6, 7, 98, 5 },
8. new int[] { 2, 5 }
9. };
10.
11. // Traverse array elements
12. for (int i = 0; i < arr.Length; i++)
13. {
14. for (int j = 0; j < arr[i].Length; j++)
15. {
16. System.Console.Write(arr[i][j]+" ");
17. }
18. System.Console.WriteLine();
19. }
20. }
21. }

Output:

11 21 56 78
2 5 6 7 98 5
2 5

Accessing Arrays Value

PROGRAMMING EXAMPLE

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace accessing_array_value
7. {
8. class Program
9. {
10. static void Main(string[] args)
11. {
12. int[] age = new int[6];
13. string[] name = new string[6];
14. int i, j = 0;
15. string find;
16.
17. // Storing users name and age in two different array.
18. for (i = 0; i < 6; i++)
19. {
20. Console.Write("\n\nEnter your name:\t");
21. name[i] = Console.ReadLine();
22. Console.Write("Enter your age:\t\t");
23. age[i] = Convert.ToInt32(Console.ReadLine());
24. }
25.
26. //Accepting name and find their correspondence age in array.
27.
28. Console.Write("\n\nEnter your name to find age:\t");
29. find = Console.ReadLine();
30.
31. for (i = 0; i < 6; i++)
32. {
33. if (name[i] == find)
34. {
35. Console.WriteLine("\n\nName\t:{0}", name[i]);
36. Console.WriteLine("Age\t:{0}", age[i]);
37. j++;
38. }
39. }
40. if (j == 0)
41. {
42. Console.WriteLine("Not Found!!!");
43. }
44. Console.ReadLine();
45. }
46. }
47. }

Output
Enter your name: Steven

Enter your age: 37

Enter your name: Clark

Enter your age: 56

Enter your name: John

Enter your age: 34

Enter your name: Smith

Enter your age: 23

Enter your name: Jack


Enter your age: 34

Enter your name: Annie

Enter your age: 23

Enter your name to find age: Jack

Name :Jack

Age :34

__

C# Params
C# Params Example 1

1. using System;
2. namespace AccessSpecifiers
3. {
4. class Program
5. {
6. // User defined function
7. public void Show(params int[] val) // Params Paramater
8. {
9. for (int i=0; i<val.Length; i++)
10. {
11. Console.WriteLine(val[i]);
12. }
13. }
14. // Main function, execution entry point of the program
15. static void Main(string[] args)
16. {
17. Program program = new Program(); // Creating Object
18. program.Show(2,4,6,8,10,12,14); // Passing arguments of variable length
19. }
20. }
21. }

Output:

2
4
6
8
10
12
14

C# Params Example 2

1. using System;
2. namespace AccessSpecifiers
3. {
4. class Program
5. {
6. // User defined function
7. public void Show(params object[] items) // Params Paramater
8. {
9. for (int i = 0; i < items.Length; i++)
10. {
11. Console.WriteLine(items[i]);
12. }
13. }
14. // Main function, execution entry point of the program
15. static void Main(string[] args)
16. {
17. Program program = new Program(); // Creating Object
18. program.Show("Ramakrishnan Ayyer","Ramesh",101, 20.50,"Peter", 'A'); // Passin
g arguments of variable length
19. }
20. }
21. }

Output:

Ramakrishnan Ayyer
Ramesh
101
20.5
Peter
A

C# Array class
C# Array Example

1. using System;
2. namespace CSharpProgram
3. {
4. class Program
5. {
6. static void Main(string[] args)
7. {
8. // Creating an array
9. int[] arr = new int[6] { 5, 8, 9, 25, 0, 7 };
10. // Creating an empty array
11. int[] arr2 = new int[6];
12. // Displaying length of array
13. Console.WriteLine("length of first array: "+arr.Length);
14. // Sorting array
15. Array.Sort(arr);
16. Console.Write("First array elements: ");
17. // Displaying sorted array
18. PrintArray(arr);
19. // Finding index of an array element
20. Console.WriteLine("\nIndex position of 25 is "+Array.IndexOf(arr,25));
21. // Coping first array to empty array
22. Array.Copy(arr, arr2, arr.Length);
23. Console.Write("Second array elements: ");
24. // Displaying second array
25. PrintArray(arr2);
26. Array.Reverse(arr);
27. Console.Write("\nFirst Array elements in reverse order: ");
28. PrintArray(arr);
29. }
30. // User defined method for iterating array elements
31. static void PrintArray(int[] arr)
32. {
33. foreach (Object elem in arr)
34. {
35. Console.Write(elem+" ");
36. }
37. }
38. }
39. }

Output:

length of first array: 6


First array elements: 0 5 7 8 9 25
Index position of 25 is 5
Second array elements: 0 5 7 8 9 25
First Array elements in reverse order: 25 9 8 7 5 0

1. Console.WriteLine("Single Dimension Array Sample");


2. // Single dim array
3. string[] strArray = new string[] {
4. "Mahesh Chand",
5. "Mike Gold",
6. "Raj Beniwal",
7. "Praveen Kumar",
8. "Dinesh Beniwal"
9. };
10. // Read array items using foreach loop
11. foreach(string str in strArray) {
12. Console.WriteLine(str);
13. }
14. Console.WriteLine("-----------------------------");
15. Console.WriteLine("Multi-Dimension Array Sample");
16. string[, ] string2DArray = new string[2, 2] {
17. {
18. "Rosy",
19. "Amy"
20. }, {
21. "Peter",
22. "Albert"
23. }
24. };
25. foreach(string str in string2DArray) {
26. Console.WriteLine(str);
27. }
28. Console.WriteLine("-----------------------------");
29. Console.WriteLine("Jagged Array Sample");
30. int[][] intJaggedArray3 = {
31. new int[] {
32. 2,
33. 12
34. },
35. new int[] {
36. 14,
37. 14,
38. 24,
39. 34
40. },
41. new int[] {
42. 6,
43. 16,
44. 26,
45. 36,
46. 46,
47. 56
48. }
49. };
50. // Loop through all itesm of a jagged array
51. for (int i = 0; i < intJaggedArray3.Length; i++) {
52. Console.Write("Element({0}): ", i);
53. for (int j = 0; j < intJaggedArray3[i].Length; j++) {
54. Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length
- 1) ? "" : " ");
55. }
56. Console.WriteLine();
57. }
58. Console.WriteLine("-----------------------------");

Listing 1

The output of Listing 1 looks like Figure 1.


Figure 1

Listing 1. Using arrays in C#.

using System;
namespace ArraysSamp
{
class Class1
{
static void Main(string[] args)
{
int[] intArray = new int[3];
intArray[0] = 3;
intArray[1] = 6;
intArray[2] = 9;
Console.WriteLine("================");
foreach (int i in intArray)
{
Console.WriteLine(i.ToString() );
}
string[] strArray = new string[5]
{"Ronnie", "Jack", "Lori", "Max", "Tricky"};
Console.WriteLine("================");
foreach( string str in strArray)
{
Console.WriteLine(str);
}
Console.WriteLine("================");
string[,] names = new string[,]
{
{"Rosy","Amy"},
{"Peter","Albert"}
};
foreach( string str in names)
{
Console.WriteLine(str);
}
Console.ReadLine();
}
}
}

The output of Listing 1 looks like Figure 1.

Write a program of sorting an array. Declare single dimensional array and accept 5 integer
values from the user. Then sort the input in ascending order and display output.

1. sing System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace Example1
7. {
8. class Program
9. {
10. static void printarray(int[] arr)
11. {
12. Console.WriteLine("\n\nElements of array are:\n");
13. foreach (int i in arr)
14. {
15. Console.Write("\t{0}", i);
16. }
17. }
18. static void Main(string[] args)
19. {
20. int[] arr = new int[5];
21. int i;
22. // loop for accepting values in array
23. for (i = 0; i < 5; i++)
24. {
25. Console.Write("Enter number:\t");
26. arr[i] = Convert.ToInt32(Console.ReadLine());
27. }
28. Program.printarray(arr);
29. //sorting array value;
30. Array.Sort(arr); //use array's sort function
31.
32. Program.printarray(arr);
33. Console.ReadLine();
34. }
35. }
36. }

Output
Enter number: 56

Enter number: 34

Enter number: 23

Enter number: 1

Enter number: 76

Elements of array are:56 34 23 1 76

Elements of array are:

1 23 34 56 76

__

Write a program to create two multidimensional arrays of same size. Accept value from user
and store them in first array. Now copy all the elements of first array are second array and
print output.
1. ng System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace example2
7. {
8. class Program
9. {
10. static void Main(string[] args)
11. {
12. int[,] arr1 = new int[3, 3];
13. int[,] arr2 = new int[3, 3];
14. int i, j;
15.
16. // Storing user input in arr1
17. for (i = 0; i < 3; i++)
18. {
19. for (j = 0; j < 3; j++)
20. {
21. Console.Write("Enter array value:\t");
22. arr1[i, j] = Convert.ToInt32(Console.ReadLine());
23. }
24. }
25. //copying value of arr1 to arr2
26. for (i = 0; i < 3; i++)
27. {
28. for (j = 0; j < 3; j++)
29. {
30. arr2[i, j] = arr1[i, j];
31. }
32. }
33.
34. Console.WriteLine("\n\nElements of second array are:\n\n");
35. //Printing the arr2 value
36. for (i = 0; i < 3; i++)
37. {
38. Console.WriteLine();
39. for (j = 0; j < 3; j++)
40. {
41. Console.Write("\t{0}", arr2[i, j]);
42. }
43. }
44. Console.ReadLine();
45. }
46. }
47. }

Output
Enter your option <1-7> for days. 1 for Monday: 9
Invalid option. Please try againEnter your option <1-7> for days. 1 for Monday: 2

Tuesday

__

Write a Program to Print One Dimensional Array in Reverse Order

1. sing System;
2.
3. namespace Sort_Array_Des
4. {
5. public class Program
6. {
7. public static void Main(string[] args)
8. {
9. int[] num= {22,50,11, 2, 49};
10. Array.Reverse(num);
11. for(int i=0; i<num.Length; i++)
12. {
13. Console.Write(num[i] + " ");
14. }
15. }
16. }
17. }
18.

Output
49 2 11 50 22 _

C# Command Line Arguments


C# Command Line Arguments Example

1. using System;
2. namespace CSharpProgram
3. {
4. class Program
5. {
6. // Main function, execution entry point of the program
7. static void Main(string[] args) // string type parameters
8. {
9. // Command line arguments
10. Console.WriteLine("Argument length: "+args.Length);
11. Console.WriteLine("Supplied Arguments are:");
12. foreach (Object obj in args)
13. {
14. Console.WriteLine(obj);
15. }
16. }
17. }
18. }

Compile and execute this program by using following commands.

Compile: csc Program.cs

Execute: Program.exe Hi there, how are you?

Output:

Argument length: 5
Supplied Arguments are:
Hi
there,
how
are
you?

C# List<T>
C# List<T> example

1. using System;
2. using System.Collections.Generic;
3.
4. public class ListExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a list of strings
9. var names = new List<string>();
10. names.Add("Sonoo Jaiswal");
11. names.Add("Ankit");
12. names.Add("Peter");
13. names.Add("Irfan");
14.
15. // Iterate list element using foreach loop
16. foreach (var name in names)
17. {
18. Console.WriteLine(name);
19. }
20. }
21. }

Output:

Sonoo Jaiswal
Ankit
Peter
Irfan

C# List<T> example using collection initializer

1. using System;
2. using System.Collections.Generic;
3.
4. public class ListExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a list of strings using collection initializer
9. var names = new List<string>() {"Sonoo", "Vimal", "Ratan", "Love" };
10.
11. // Iterate through the list.
12. foreach (var name in names)
13. {
14. Console.WriteLine(name);
15. }
16. }
17. }
Output:

Sonoo
Vimal
Ratan
Love

C# HashSet<T>
C# HashSet<T> example

1. sing System;
2. using System.Collections.Generic;
3.
4. public class HashSetExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a set of strings
9. var names = new HashSet<string>();
10. names.Add("Sonoo");
11. names.Add("Ankit");
12. names.Add("Peter");
13. names.Add("Irfan");
14. names.Add("Ankit");//will not be added
15.
16. // Iterate HashSet elements using foreach loop
17. foreach (var name in names)
18. {
19. Console.WriteLine(name);
20. }
21. }
22. }

Output:

Sonoo
Ankit
Peter
Irfan

C# HashSet<T> example 2
1. using System;
2. using System.Collections.Generic;
3.
4. public class HashSetExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a set of strings
9. var names = new HashSet<string>(){"Sonoo", "Ankit", "Peter", "Irfan"};
10.
11. // Iterate HashSet elements using foreach loop
12. foreach (var name in names)
13. {
14. Console.WriteLine(name);
15. }
16. }
17. }

Output:

Sonoo
Ankit
Peter
Irfan

C# SortedSet<T>
C# SortedSet<T> example

1. using System;
2. using System.Collections.Generic;
3.
4. public class SortedSetExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a set of strings
9. var names = new SortedSet<string>();
10. names.Add("Sonoo");
11. names.Add("Ankit");
12. names.Add("Peter");
13. names.Add("Irfan");
14. names.Add("Ankit");//will not be added
15.
16. // Iterate SortedSet elements using foreach loop
17. foreach (var name in names)
18. {
19. Console.WriteLine(name);
20. }
21. }
22. }

Output:

Ankit
Irfan
Peter
Sonoo

C# SortedSet<T> ex

1. using System;
2. using System.Collections.Generic;
3.
4. public class SortedSetExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a set of strings
9. var names = new SortedSet<string>(){"Sonoo", "Ankit", "Peter", "Irfan"};
10.
11. // Iterate SortedSet elements using foreach loop
12. foreach (var name in names)
13. {
14. Console.WriteLine(name);
15. }
16. }
17. }

Output:
Ankit
Irfan
Peter
Sonoo

C# Stack<T>
C# Stack<T> example

1. using System;
2. using System.Collections.Generic;
3.
4. public class StackExample
5. {
6. public static void Main(string[] args)
7. {
8. Stack<string> names = new Stack<string>();
9. names.Push("Sonoo");
10. names.Push("Peter");
11. names.Push("James");
12. names.Push("Ratan");
13. names.Push("Irfan");
14.
15. foreach (string name in names)
16. {
17. Console.WriteLine(name);
18. }
19.
20. Console.WriteLine("Peek element: "+names.Peek());
21. Console.WriteLine("Pop: "+ names.Pop());
22. Console.WriteLine("After Pop, Peek element: " + names.Peek());
23.
24. }
25. }

Output:

Sonoo
Peter
James
Ratan
Irfan
Peek element: Irfan
Pop: Irfan
After Pop, Peek element: Ratan

C# Queue<T>
C# Queue<T> example

1. sing System;
2. using System.Collections.Generic;
3.
4. public class QueueExample
5. {
6. public static void Main(string[] args)
7. {
8. Queue<string> names = new Queue<string>();
9. names.Enqueue("Sonoo");
10. names.Enqueue("Peter");
11. names.Enqueue("James");
12. names.Enqueue("Ratan");
13. names.Enqueue("Irfan");
14.
15. foreach (string name in names)
16. {
17. Console.WriteLine(name);
18. }
19.
20. Console.WriteLine("Peek element: "+names.Peek());
21. Console.WriteLine("Dequeue: "+ names.Dequeue());
22. Console.WriteLine("After Dequeue, Peek element: " + names.Peek());
23. }
24. }

Output:

Sonoo
Peter
James
Ratan
Irfan
Peek element: Sonoo
Dequeue: Sonoo
After Dequeue, Peek element: Peter

C# LinkedList<T>
C# LinkedList<T> example

1. using System;
2. using System.Collections.Generic;
3.
4. public class LinkedListExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a list of strings
9. var names = new LinkedList<string>();
10. names.AddLast("Sonoo Jaiswal");
11. names.AddLast("Ankit");
12. names.AddLast("Peter");
13. names.AddLast("Irfan");
14. names.AddFirst("John");//added to first index
15.
16. // Iterate list element using foreach loop
17. foreach (var name in names)
18. {
19. Console.WriteLine(name);
20. }
21. }
22. }

Output:

John
Sonoo Jaiswal
Ankit
Peter
Irfan

initializer.
C# LinkedList<T> example 2

1. using System;
2. using System.Collections.Generic;
3.
4. public class LinkedListExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a list of strings
9. var names = new LinkedList<string>();
10. names.AddLast("Sonoo");
11. names.AddLast("Ankit");
12. names.AddLast("Peter");
13. names.AddLast("Irfan");
14.
15. //insert new element before "Peter"
16. LinkedListNode<String> node=names.Find("Peter");
17. names.AddBefore(node, "John");
18. names.AddAfter(node, "Lucy");
19.
20. // Iterate list element using foreach loop
21. foreach (var name in names)
22. {
23. Console.WriteLine(name);
24. }
25. }
26. }

Output:

Sonoo
Ankit
John
Peter
Lucy
Irfan
C# Dictionary<TKey, TValue>
C# Dictionary<TKey, TValue> example

1. using System;
2. using System.Collections.Generic;
3.
4. public class DictionaryExample
5. {
6. public static void Main(string[] args)
7. {
8. Dictionary<string, string> names = new Dictionary<string, string>();
9. names.Add("1","Sonoo");
10. names.Add("2","Peter");
11. names.Add("3","James");
12. names.Add("4","Ratan");
13. names.Add("5","Irfan");
14.
15. foreach (KeyValuePair<string, string> kv in names)
16. {
17. Console.WriteLine(kv.Key+" "+kv.Value);
18. }
19. }
20. }

Output:

1 Sonoo
2 Peter
3 James
4 Ratan
5 Irfan

C# SortedDictionary<TKey, TValue>
C# SortedDictionary<TKey, TValue> example

1. using System;
2. using System.Collections.Generic;
3.
4. public class SortedDictionaryExample
5. {
6. public static void Main(string[] args)
7. {
8. SortedDictionary<string, string> names = new SortedDictionary<string, string>()
;
9. names.Add("1","Sonoo");
10. names.Add("4","Peter");
11. names.Add("5","James");
12. names.Add("3","Ratan");
13. names.Add("2","Irfan");
14. foreach (KeyValuePair<string, string> kv in names)
15. {
16. Console.WriteLine(kv.Key+" "+kv.Value);
17. }
18. }
19. }

Output:

1 Sonoo
2 Irfan
3 Ratan
4 Peter
5 James

C# SortedList<TKey, TValue>

C# SortedList<TKey, TValue> example

1. using System;
2. using System.Collections.Generic;
3.
4. public class SortedDictionaryExample
5. {
6. public static void Main(string[] args)
7. {
8. SortedList<string, string> names = new SortedList<string, string>();
9. names.Add("1","Sonoo");
10. names.Add("4","Peter");
11. names.Add("5","James");
12. names.Add("3","Ratan");
13. names.Add("2","Irfan");
14. foreach (KeyValuePair<string, string> kv in names)
15. {
16. Console.WriteLine(kv.Key+" "+kv.Value);
17. }
18. }
19. }

Output:

1 Sonoo
2 Irfan
3 Ratan
4 Peter
5 James

C# Generics
C# Generic class example

1. using System;
2. namespace CSharpProgram
3. {
4. class GenericClass<T>
5. {
6. public GenericClass(T msg)
7. {
8. Console.WriteLine(msg);
9. }
10. }
11. class Program
12. {
13. static void Main(string[] args)
14. {
15. GenericClass<string> gen = new GenericClass<string> ("This is generic cla
ss");
16. GenericClass<int> genI = new GenericClass<int>(101);
17. GenericClass<char> getCh = new GenericClass<char>('I');
18. }
19. }
20. }

Output:

This is generic class


101
I

Generic Method Example

1. using System;
2. namespace CSharpProgram
3. {
4. class GenericClass
5. {
6. public void Show<T>(T msg)
7. {
8. Console.WriteLine(msg);
9. }
10. }
11. class Program
12. {
13. static void Main(string[] args)
14. {
15. GenericClass genC = new GenericClass();
16. genC.Show("This is generic method");
17. genC.Show(101);
18. genC.Show('I');
19. }
20. }
21. }

Output:
This is generic method
101
I

C# Delegates
C# Delegate Example
1. sing System;
2. delegate int Calculator(int n);//declaring delegate
3.
4. public class DelegateExample
5. {
6. static int number = 100;
7. public static int add(int n)
8. {
9. number = number + n;
10. return number;
11. }
12. public static int mul(int n)
13. {
14. number = number * n;
15. return number;
16. }
17. public static int getNumber()
18. {
19. return number;
20. }
21. public static void Main(string[] args)
22. {
23. Calculator c1 = new Calculator(add);//instantiating delegate
24. Calculator c2 = new Calculator(mul);
25. c1(20);//calling method using delegate
26. Console.WriteLine("After c1 delegate, Number is: " + getNumber());
27. c2(3);
28. Console.WriteLine("After c2 delegate, Number is: " + getNumber());
29.
30. }
31. }
Output:

After c1 delegate, Number is: 120


After c2 delegate, Number is: 360

c# Reflection

C# Reflection Example: Get Type


1. using System;
2. public class ReflectionExample
3. {
4. public static void Main()
5. {
6. int a = 10;
7. Type type = a.GetType();
8. Console.WriteLine(type);
9. }
10. }

Output:

System.Int32

# Reflection Example: Print Type Information


1. using System;
2. using System.Reflection;
3. public class ReflectionExample
4. {
5. public static void Main()
6. {
7. Type t = typeof(System.String);
8. Console.WriteLine(t.FullName);
9. Console.WriteLine(t.BaseType);
10. Console.WriteLine(t.IsClass);
11. Console.WriteLine(t.IsEnum);
12. Console.WriteLine(t.IsInterface);
13. }
14. }

Output:
System.String
System.Object
true
false
false

C# Reflection Example: Print Constructors


1. using System;
2. using System.Reflection;
3. public class ReflectionExample
4. {
5. public static void Main()
6. {
7. Type t = typeof(System.String);
8.
9. Console.WriteLine("Constructors of {0} type...", t);
10. ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);

11. foreach (ConstructorInfo c in ci)


12. {
13. Console.WriteLine(c);
14. }
15. }
16. }

Output:

Constructors of System.String type...


Void .ctor(Char*)
Void .ctor(Char*, Int32, Int32)
Void .ctor(SByte*)
Void .ctor(SByte*, Int32, Int32)
Void .ctor(SByte*, Int32, Int32, System.Text.Encoding)
Void .ctor(Char[], Int32, Int32)
Void .ctor(Char[])
Void .ctor(Char, Int32)

C# Reflection Example: Print Methods


1. using System;
2. using System.Reflection;
3. public class ReflectionExample
4. {
5. public static void Main()
6. {
7. Type t = typeof(System.String);
8.
9. Console.WriteLine("Methods of {0} type...", t);
10. MethodInfo[] ci = t.GetMethods(BindingFlags.Public | BindingFlags.Instance);
11. foreach (MethodInfo m in ci)
12. {
13. Console.WriteLine(m);
14. }
15. }
16. }

Output:

Methods of System.String type...


Boolean Equals(System.Object)
Boolean Equals(System.String)
Boolean Equals(System.String, System.StringComparison)
Char get_Chars(Int32)
Void copyTo(Int32, char[], Int32, Int32)
Char[] ToCharArray()
....

C# Reflection Example: Print Fields


1. using System;
2. using System.Reflection;
3. public class ReflectionExample
4. {
5. public static void Main()
6. {
7. Type t = typeof(System.String);
8.
9. Console.WriteLine("Fields of {0} type...", t);
10. FieldInfo[] ci = t.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.Non
Public);
11. foreach (FieldInfo f in ci)
12. {
13. Console.WriteLine(f);
14. }
15. }
16. }

Output:
Fields of System.String type...
System.String Empty
Int32 TrimHead
Int32 TrimTail
Int32 TrimBoth
Int32 charPtrAlignConst
Int32 alignConst

C# Anonymous Functions
C# Lambda Expressions

Example

1. using System;
2. namespace LambdaExpressions
3. {
4. class Program
5. {
6. delegate int Square(int num);
7. static void Main(string[] args)
8. {
9. Square GetSquare = x => x * x;
10. int j = GetSquare(5);
11. Console.WriteLine("Square: "+j);
12. }
13. }
14. }

Output:

Square: 25

C# Anonymous Methods
1. using System;
2. namespace AnonymousMethods
3. {
4. class Program
5. {
6. public delegate void AnonymousFun();
7. static void Main(string[] args)
8. {
9. AnonymousFun fun = delegate () {
10. Console.WriteLine("This is anonymous function");
11. };
12. fun();
13. }
14. }
15. }

Output:

This is anonymous function

C# Generics Programming
1. }

PROGRAMMING EXAMPLE

1. using System;
2. using System.Collections.Generic;
3.
4. namespace Generics_Example
5. {
6. //Declare Generics
7. public class GenClass<T>
8. {
9. public void GenFunction(T printvalue)
10. {
11. Console.WriteLine(printvalue);
12. }
13. }
14. public class Program
15. {
16. public static void Main(string[] args)
17. {
18. Console.WriteLine("Printing Integer Value");
19. GenClass<int> gen=new GenClass<int>();
20. gen.GenFunction(144);
21.
22. Console.WriteLine("Printing String Value");
23. GenClass<string> genstring=new GenClass<string>();
24. genstring.GenFunction("Hello String");
25. }
26. }
27. }

Output
Printing Integer Value

144

Printing String Value

Hello String

C# FileStream
C# FileStream example: writing single byte into file

Let's see the simple example of FileStream class to write single byte of data into file. Here,
we are using OpenOrCreate file mode which can be used for read and write operations.

1. using System;
2. using System.IO;
3. public class FileStreamExample
4. {
5. public static void Main(string[] args)
6. {
7. FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);//creating file
stream
8. f.WriteByte(65);//writing byte into stream
9. f.Close();//closing stream
10. }
11. }

Output:

A
C# FileStream example: writing multiple bytes into file

Let's see another example to write multiple bytes of data into file using loop.

1. using System;
2. using System.IO;
3. public class FileStreamExample
4. {
5. public static void Main(string[] args)
6. {
7. FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);
8. for (int i = 65; i <= 90; i++)
9. {
10. f.WriteByte((byte)i);
11. }
12. f.Close();
13. }
14. }

Output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

C# FileStream example: reading all bytes from file

Let's see the example of FileStream class to read data from the file. Here, ReadByte()
method of FileStream class returns single byte. To all read all the bytes, you need to use
loop.

1. using System;
2. using System.IO;
3. public class FileStreamExample
4. {
5. public static void Main(string[] args)
6. {
7. FileStream f = new FileStream("e:\\b.txt", FileMode.OpenOrCreate);
8. int i = 0;
9. while ((i = f.ReadByte()) != -1)
10. {
11. Console.Write((char)i);
12. }
13. f.Close();
14. }
15. }

Output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

C# StreamWriter
C# StreamWriter example
Let's see a simple example of StreamWriter class which writes a single line of data into the
file.

1. using System;
2. using System.IO;
3. public class StreamWriterExample
4. {
5. public static void Main(string[] args)
6. {
7. FileStream f = new FileStream("e:\\output.txt", FileMode.Create);
8. StreamWriter s = new StreamWriter(f);
9.
10. s.WriteLine("hello c#");
11. s.Close();
12. f.Close();
13. Console.WriteLine("File created successfully...");
14. }
15. }

Output:

File created successfully...


Now open the file, you will see the text "hello c#" in output.txt file.

output.txt:

hello c#

C# StreamReader
1. sing System;
2. using System.IO;
3. public class StreamReaderExample
4. {
5. public static void Main(string[] args)
6. {
7. FileStream f = new FileStream("e:\\output.txt", FileMode.OpenOrCreate);
8. StreamReader s = new StreamReader(f);
9.
10. string line=s.ReadLine();
11. Console.WriteLine(line);
12.
13. s.Close();
14. f.Close();
15. }
16. }

Output:

Hello C#

C# StreamReader example to read all lines

1. using System;
2. using System.IO;
3. public class StreamReaderExample
4. {
5. public static void Main(string[] args)
6. {
7. FileStream f = new FileStream("e:\\a.txt", FileMode.OpenOrCreate);
8. StreamReader s = new StreamReader(f);
9.
10. string line = "";
11. while ((line = s.ReadLine()) != null)
12. {
13. Console.WriteLine(line);
14. }
15. s.Close();
16. f.Close();
17. }
18. }

Output:

Hello C#
this is file handling

Next Topic C# TextWriter

C# Serialization example
1. sing System;
2. using System.IO;
3. using System.Runtime.Serialization.Formatters.Binary;
4. [Serializable]
5. class Student
6. {
7. int rollno;
8. string name;
9. public Student(int rollno, string name)
10. {
11. this.rollno = rollno;
12. this.name = name;
13. }
14. }
15. public class SerializeExample
16. {
17. public static void Main(string[] args)
18. {
19. FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);
20. BinaryFormatter formatter=new BinaryFormatter();
21.
22. Student s = new Student(101, "sonoo");
23. formatter.Serialize(stream, s);
24.
25. stream.Close();
26. }
27. }

sss.txt:

JConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null


Student rollnoname e sonoo

As you can see, the serialized data is stored in the file. To get the data, you need to perform
deserialization.

Next Topic C# Deserial

# Deserialization Example
Let's see the simple example of deserialization in C#.

1. using System;
2. using System.IO;
3. using System.Runtime.Serialization.Formatters.Binary;
4. [Serializable]
5. class Student
6. {
7. public int rollno;
8. public string name;
9. public Student(int rollno, string name)
10. {
11. this.rollno = rollno;
12. this.name = name;
13. }
14. }
15. public class DeserializeExample
16. {
17. public static void Main(string[] args)
18. {
19. FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);
20. BinaryFormatter formatter=new BinaryFormatter();
21.
22. Student s=(Student)formatter.Deserialize(stream);
23. Console.WriteLine("Rollno: " + s.rollno);
24. Console.WriteLine("Name: " + s.name);
25.
26. stream.Close();
27. }
28. }

Output:

Rollno: 101
Name: sonoo

Das könnte Ihnen auch gefallen