CSharp MidTerm
CSharp MidTerm
Boolean Conditions
Automatic Garbage Collection
Standard Library
Assembly Versioning
Properties and Events
Delegates and Events Management
Easy-to-use Generics
Indexers
Conditional Compilation
Simple Multithreading
LINQ and Lambda Expressions
Integration with Windows
We have already mentioned that C# is part of .Net framework and is used for writing .Net
applications. Therefore, before discussing the available tools for running a C# program,
let us understand how C# relates to the .Net framework.
Windows applications
Web applications
Web services
The .Net framework applications are multi-platform applications. The framework has
been designed in such a way that it can be used from any of the following languages:
C#, C++, Visual Basic, Jscript, COBOL, etc. All these languages can access the
framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client
languages such as C#. Following are some of the components of the .Net framework −
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Let us look at a simple code that prints the words "Hello World" −
Live Demo
using System;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled and executed, it produces the following result −
Hello World
Let us look at the various parts of the given program −
The first line of the program using System; - the using keyword is used to
include the System namespace in the program. A program generally has
multiple using statements.
The using keyword states that the program is using the names in the given
namespace. For example, we are using the System namespace in our programs.
The class Console is defined there. We just write −
Console.WriteLine ("Hello there");
We could have written the fully qualified name as −
System.Console.WriteLine("Hello there");
The next line has a class declaration, the class HelloWorld contains the data and
method definitions that your program uses. Classes generally contain multiple
methods. Methods define the behavior of the class. However,
the HelloWorld class has only one method Main.
The next line defines the Main method, which is the entry point for all C#
programs. The Main method states what the class does when executed.
The next line /*...*/ is ignored by the compiler and it is put to add comments in the
program.
The Main method specifies its behavior with the
statement Console.WriteLine("Hello World");
WriteLine is a method of the Console class defined in the System namespace.
This statement causes the message "Hello, World!" to be displayed on the screen.
The last line Console.ReadKey(); is for the VS.NET Users. This makes the
program wait for a key press and it prevents the screen from running and closing
quickly when the program is launched from Visual Studio .NET.
It is worth to note the following points −
C# is case sensitive.
All statements and expression must end with a semicolon (;).
The program execution starts at the Main method.
Unlike Java, program file name could be different from the class name.
In the following example, we are passing command line arguments during execution of
program.
After executing the code, it produces the following output to the console.
Output:
Argument length: 5
Supplied Arguments are:
Hi
there,
how
are
you?
Live Demo
using System;
namespace RectangleApplication {
class Rectangle {
// member variables
double length;
double width;
Comments in C#
Comments are used for explaining code. Compilers ignore the comment entries. The multiline
comments in C# programs start with /* and terminates with the characters */ as shown below −
/* This program demonstrates
The basic syntax of C# programming
Language */
Single-line comments are indicated by the '//' symbol. For example,
}//end class Rectangle
Member Variables
Variables are attributes or data members of a class, used for storing data. In the preceding
program, the Rectangle class has two member variables named length and width.
Member Functions
Functions are set of statements that perform a specific task. The member functions of a class are
declared within the class. Our sample class Rectangle contains three member
functions: AcceptDetails, GetArea and Display.
Instantiating a Class
In the preceding program, the class ExecuteRectangle contains the Main() method and
instantiates the Rectangle class.
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item.
The basic rules for naming classes in C# are as follows −
A name must begin with a letter that could be followed by a sequence of letters, digits (0
- 9) or underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } .
; : " ' / and \. However, an underscore ( _ ) can be used.
It should not be a C# keyword.
C# Keywords
Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as
identifiers. However, if you want to use these keywords as identifiers, you may prefix the
keyword with the @ character.
In C#, some identifiers have special meaning in context of code, such as get and set are called
contextual keywords.
The following table lists the reserved keywords and contextual keywords in C# −
Reserved Keywords
volatile while
Contextual Keywords
Step 3: Repeat the step 2 until the number is greater than zero
1. using System;
2. public class ConversionExample
3. {
4. public static void Main(string[] args)
5. {
6. int n, i;
7. int[] a = new int[10];
8. Console.Write("Enter the number to convert: ");
9. n= int.Parse(Console.ReadLine());
10. for(i=0; n>0; i++)
11. {
12. a[i]=n%2;
13. n= n/2;
14. }
15. Console.Write("Binary of the given number= ");
16. for(i=i-1 ;i>=0 ;i--)
17. {
18. Console.Write(a[i]);
19. }
20. }
21. }
C# If-else Example: with input from user
In this example, we are getting input from the user
using Console.ReadLine() method. It returns string. For numeric value, you need to
convert it into int using Convert.ToInt32() method.
1. using 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
C# Switch Example
The C# switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement in C#.
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
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
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
1. using 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:
1
2
3
4
5
6
7
8
9
10
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. }
C# Break Statement
The C# break is used to break loop or switch statement. It breaks the current flow of
the program at the given condition. In case of inner loop, it breaks only inner loop.
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# Continue Statement
The C# continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.
Output:
1
2
3
4
6
7
8
9
10
C# Goto Statement
The C# goto statement is also known jump statement. It is used to transfer control to
the other part of the program. It unconditionally jumps to the specified label.
It can be used to transfer control from deeply nested loop or switch case label.
Currently, it is avoided to use goto statement in C# because it makes the program
complex.
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:
Return type: It is used to specify the data type of function return value.
Parameters: It is a list of arguments that we can pass to the function during call.
C# Function Syntax
1. <access-specifier><return-type>FunctionName(<parameters>)
2. {
3. // function body
4. // return statement
5. }
Let's see an example in which we have created a function that returns a string value
and takes a string parameter.
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:
Output:
Hello Rahul Kumar
A function can have zero or any number of parameters to get data. In the following
example, a function is created without parameters. A function without parameter is also
known as non-parameterized function.
Output:
C# Call By Reference
C# provides a ref keyword to pass argument as reference-type. It passes reference of
arguments to the function rather than copy of original value. The changes in passed
values are permanent and modify the original variable value.
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:
Advantages of C# Array
o Code Optimization (less code)
o Random Access
Disadvantages of C# Array
o Fixed size
C# Array Types
There are 3 types of arrays in C# programming:
2. Multidimensional Array
3. Jagged Array
C# Single Dimensional Array
To create single dimensional array, you need to use square brackets [] after the type.
Let's see a simple example of C# array, where we are going to declare, initialize and
traverse array.
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
There are 3 ways to initialize array at the time of declaration.
Let's see the example of array where we are declaring and initializing array at the 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
We can also traverse the array elements using foreach loop. It returns array element
one by one.
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
# Passing Array to Function Example: Print minimum number
Let's see an example of C# array which prints minimum number in an array using
function.
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:
To create multidimensional array, we need to use comma inside the square brackets.
For 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 Array Example: Declaration and
initialization at same time
There are 3 ways to initialize multidimensional array in C# while declaration.
1. int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Let's see a simple example of multidimensional array which initializes array at the time
of declaration.
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
For arrays, you need to define the number of elements that the array can hold
at the time of array declaration. But in the case of the Array List collection, this
does not need to be done beforehand. Elements can be added or removed
from the Array List collection at any point in time. Let's look at the operations
available for the array list collection in more detail.
In the program below, we will write the code to create a new array list. We will
also show to add elements and to display the elements of the Array list.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
ArrayList a1 = new ArrayList();
a1.Add(1);
a1.Add("Example");
a1.Add(true);
Console.WriteLine(a1[0]);
Console.WriteLine(a1[1]);
Console.WriteLine(a1[2]);
Console.ReadKey();
}
}
}
Code Explanation:-
1. The first step is used to declare our Array List. Here we are declaring a1
as a variable to hold the elements of our array list.
2. We then use the add keyword to add the number 1 , the String
"Example" and the Boolean value 'true' to the array list.
3. We then use the Console.WriteLine method to display the value of each
array lists element to the console. You will notice that just like arrays,
we can access the elements via their index positions. So to access the
first position of the Array List, we use the [0] index position. And so on
and so forth.
Jagged array
Jagged array is a array of arrays such that member arrays can be of different
sizes. In other words, the length of each array index can differ. The elements of
Jagged Array are reference types and initialized to null by default. Jagged Array
can also be mixed with multidimensional arrays. Here, the number of rows will
be fixed at the declaration time, but you can vary the number of columns.
Declaration
In Jagged arrays, user has to provide the number of rows only. If the user is
also going to provide the number of columns, then this array will be no more
Jagged Array.
Syntax:
data_type[][] name_of_array = new data_type[rows][]
Example:
int[][] jagged_arr = new int[4][]
In the above example, a single-dimensional array is declared that has 4
elements(rows), each of which is a 1-D array of integers.
Initialization
The elements of Jagged Array must be initialized before its use. You can
separately initialize each array element. There are many ways to initialize the
Jagged array’s element.
Example 1: Providing the size of each array elements separately. Here each of
the elements is a 1-D array of integers where:
The first row or element is an array of 2 integers.
The second row or element is an array of 4 integers.
The third row or element is an array of 6 integers.
The fourth row or element is an array of 7 integers.
jagged_arr[0] = new int[2];
jagged_arr[1] = new int[4];
jagged_arr[2] = new int[6];
jagged_arr[3] = new int[7];
Example 2: When the array size is not needed then its elements can be
initialized with direct values as follows:
jagged_arr[0] = new int[] {1, 2, 3, 4};
jagged_arr[1] = new int[] {11, 34, 67};
jagged_arr[2] = new int[] {89, 23};
jagged_arr[3] = new int[] {0, 45, 78, 53, 99};
Declaration as well as Initialization
Example 1: Using the Direct Method
int[][] jagged_arr = new int[][]
{
new int[] {1, 2, 3, 4},
new int[] {11, 34, 67},
new int[] {89, 23},
new int[] {0, 45, 78, 53, 99}
};
Example 2: Using Short-hand Method. There is no default initialization for the
elements so a user cannot omit the new operator from the elements
initialization.
int[][] jagged_arr =
{
new int[] {1, 2, 3, 4},
new int[] {11, 34, 67},
new int[] {89, 23},
new int[] {0, 45, 78, 53, 99}
};
Accessing the Elements
To access the elements of the Jagged array user has to specify the row and
column with the array name.
Example:
// Accessing & Assigning 99 to the third element ([2]) of the second
array ([1])
jagged_arr[1][2] = 99;
using System;
class GFG {
// Main Method
System.Console.WriteLine();
Output:
Row(0): 1 2 3 4
Row(1): 11 34 67
Row(2): 89 23
Row(3): 0 45 78 53 99
C# Object and Class
Since C# is an object-oriented language, program is designed using objects and classes
in C#.
C# Object
In C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data
and behavior means functionality.
Object is an instance of a class. All the members of the class can be accessed through
object.
In this example, Student is the type and s1 is the reference variable that refers to the
instance of Student class. The new keyword allocates memory at runtime.
C# Class
In C#, class is a group of similar objects. It is a template from which objects are
created. It can have fields, methods, constructors etc.
1. using System;
2. public class Student
3. {
4. int id;//data member (also instance variable)
5. String name;//data member(also instance variable)
6.
7. public static void Main(string[] args)
8. {
9. Student s1 = new Student();//creating an object of Student
10. s1.id = 101;
11. s1.name = "Sonoo Jaiswal";
12. Console.WriteLine(s1.id);
13. Console.WriteLine(s1.name);
14.
15. }
16. }
Output:
101
Sonoo Jaiswal
C# Class Example 2: Having Main() in another class
Let's see another example of class where we are having Main() method in another
class. In such case, class must be public.
1. using System;
2. public class Student
3. {
4. public int id;
5. public String name;
6. }
7. class TestStudent{
8. public static void Main(string[] args)
9. {
10. Student s1 = new Student();
11. s1.id = 101;
12. s1.name = "Sonoo Jaiswal";
13. Console.WriteLine(s1.id);
14. Console.WriteLine(s1.name);
15.
16. }
17. }
Output:
101
Sonoo Jaiswal
C# Class Example 3: Initialize and Display data through
method
Let's see another example of C# class where we are initializing and displaying object
through method.
1. using System;
2. public class Student
3. {
4. public int id;
5. public String name;
6. public void insert(int i, String n)
7. {
8. id = i;
9. name = n;
10. }
11. public void display()
12. {
13. Console.WriteLine(id + " " + name);
14. }
15. }
16. class TestStudent{
17. public static void Main(string[] args)
18. {
19. Student s1 = new Student();
20. Student s2 = new Student();
21. s1.insert(101, "Ajeet");
22. s2.insert(102, "Tom");
23. s1.display();
24. s2.display();
25.
26. }
27. }
Output:
101 Ajeet
102 Tom
C# Class Example 4: Store and Display Employee
Information
1. using System;
2. public class Employee
3. {
4. public int id;
5. public String name;
6. public float salary;
7. public void insert(int i, String n,float s)
8. {
9. id = i;
10. name = n;
11. salary = s;
12. }
13. public void display()
14. {
15. Console.WriteLine(id + " " + name+" "+salary);
16. }
17. }
18. class TestEmployee{
19. public static void Main(string[] args)
20. {
21. Employee e1 = new Employee();
22. Employee e2 = new Employee();
23. e1.insert(101, "Sonoo",890000f);
24. e2.insert(102, "Mahesh", 490000f);
25. e1.display();
26. e2.display();
27.
28. }
29. }
Output:
C# Constructor
In C#, constructor is a special method which is invoked automatically at the time of
object creation. It is used to initialize the data members of new object generally. The
constructor in C# has the same name as class or struct.
o Default constructor
o Parameterized constructor
C# Default Constructor
A constructor which has no argument is known as default constructor. It is invoked at
the time of creating object.
Output:
1. using System;
2. public class Employee
3. {
4. public Employee()
5. {
6. Console.WriteLine("Default Constructor Invoked");
7. }
8. }
9. class TestEmployee{
10. public static void Main(string[] args)
11. {
12. Employee e1 = new Employee();
13. Employee e2 = new Employee();
14. }
15. }
Output:
C# Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to
provide different values to distinct objects.
1. using System;
2. public class Employee
3. {
4. public int id;
5. public String name;
6. public float salary;
7. public Employee(int i, String n,float s)
8. {
9. id = i;
10. name = n;
11. salary = s;
12. }
13. public void display()
14. {
15. Console.WriteLine(id + " " + name+" "+salary);
16. }
17. }
18. class TestEmployee{
19. public static void Main(string[] args)
20. {
21. Employee e1 = new Employee(101, "Sonoo", 890000f);
22. Employee e2 = new Employee(102, "Mahesh", 490000f);
23. e1.display();
24. e2.display();
25.
26. }
27. }
Output:
1. using System;
2. public class Employee
3. {
4. public Employee()
5. {
6. Console.WriteLine("Constructor Invoked");
7. }
8. ~Employee()
9. {
10. Console.WriteLine("Destructor Invoked");
11. }
12. }
13. class TestEmployee{
14. public static void Main(string[] args)
15. {
16. Employee e1 = new Employee();
17. Employee e2 = new Employee();
18. }
19. }
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
Note: Destructor can't be public. We can't apply any modifier on destructors.
C# this
In c# programming, this is a keyword that refers to the current instance of the class.
There can be 3 main usage of this keyword in C#.
C# this example
Let's see the example of this keyword in C# that refers to the fields of current class.
1. using System;
2. public class Employee
3. {
4. public int id;
5. public String name;
6. public float salary;
7. public Employee(int id, String name,float salary)
8. {
9. this.id = id;
10. this.name = name;
11. this.salary = salary;
12. }
13. public void display()
14. {
15. Console.WriteLine(id + " " + name+" "+salary);
16. }
17. }
18. class TestEmployee{
19. public static void Main(string[] args)
20. {
21. Employee e1 = new Employee(101, "Sonoo", 890000f);
22. Employee e2 = new Employee(102, "Mahesh", 490000f);
23. e1.display();
24. e2.display();
25.
26. }
27. }
Output:
C# static
In C#, static is a keyword or modifier that belongs to the type not instance. So instance
is not required to access the static members. In C#, static can be field, method,
constructor, class, properties, operator and event.
C# Static Field
A field which is declared as static, is called static field. Unlike instance field which gets
memory each time whenever you create object, there is only one copy of static field
created in the memory. It is shared to all the objects.
It is used to refer the common property of all objects such as rateOfInterest in case of
Account, companyName in case of Employee etc.
1. using System;
2. public class Account
3. {
4. public int accno;
5. public String name;
6. public static float rateOfInterest=8.8f;
7. public Account(int accno, String name)
8. {
9. this.accno = accno;
10. this.name = name;
11. }
12.
13. public void display()
14. {
15. Console.WriteLine(accno + " " + name + " " + rateOfInterest);
16. }
17. }
18. class TestAccount{
19. public static void Main(string[] args)
20. {
21. Account a1 = new Account(101, "Sonoo");
22. Account a2 = new Account(102, "Mahesh");
23. a1.display();
24. a2.display();
25.
26. }
27. }
Output:
1. using System;
2. public class Account
3. {
4. public int accno;
5. public String name;
6. public static float rateOfInterest=8.8f;
7. public Account(int accno, String name)
8. {
9. this.accno = accno;
10. this.name = name;
11. }
12.
13. public void display()
14. {
15. Console.WriteLine(accno + " " + name + " " + rateOfInterest);
16. }
17. }
18. class TestAccount{
19. public static void Main(string[] args)
20. {
21. Account.rateOfInterest = 10.5f;//changing value
22. Account a1 = new Account(101, "Sonoo");
23. Account a2 = new Account(102, "Mahesh");
24. a1.display();
25. a2.display();
26.
27. }
28. }
Output:
1. using System;
2. public class Account
3. {
4. public int accno;
5. public String name;
6. public static int count=0;
7. public Account(int accno, String name)
8. {
9. this.accno = accno;
10. this.name = name;
11. count++;
12. }
13.
14. public void display()
15. {
16. Console.WriteLine(accno + " " + name);
17. }
18. }
19. class TestAccount{
20. public static void Main(string[] args)
21. {
22. Account a1 = new Account(101, "Sonoo");
23. Account a2 = new Account(102, "Mahesh");
24. Account a3 = new Account(103, "Ajeet");
25. a1.display();
26. a2.display();
27. a3.display();
28. Console.WriteLine("Total Objects are: "+Account.count);
29. }
30. }
Output:
101 Sonoo
102 Mahesh
103 Ajeet
Total Objects are: 3
C# static class
The C# static class is like the normal class but it cannot be instantiated. It can have
only static members. The advantage of static class is that it provides you guarantee
that instance of static class cannot be created.
1. using System;
2. public static class MyMath
3. {
4. public static float PI=3.14f;
5. public static int cube(int n){return n*n*n;}
6. }
7. class TestMyMath{
8. public static void Main(string[] args)
9. {
10. Console.WriteLine("Value of PI is: "+MyMath.PI);
11. Console.WriteLine("Cube of 3 is: " + MyMath.cube(3));
12. }
13. }
Output:
1. using System;
2. public class Account
3. {
4. public int id;
5. public String name;
6. public static float rateOfInterest;
7. public Account(int id, String name)
8. {
9. this.id = id;
10. this.name = name;
11. }
12. static Account()
13. {
14. rateOfInterest = 9.5f;
15. }
16. public void display()
17. {
18. Console.WriteLine(id + " " + name+" "+rateOfInterest);
19. }
20. }
21. class TestEmployee{
22. public static void Main(string[] args)
23. {
24. Account a1 = new Account(101, "Sonoo");
25. Account a2 = new Account(102, "Mahesh");
26. a1.display();
27. a2.display();
28.
29. }
30. }
Output:
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member for your program.
For example, here is the way you can declare the Book structure −
struct Books {
public string title;
public string author;
public string subject;
public int book_id;
};
The following program shows the use of the structure −
Live Demo
using System;
struct Books {
public string title;
public string author;
public string subject;
public int book_id;
};
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Features of C# Structures
You have already used a simple structure named Books. Structures in C# are quite
different from that in traditional C or C++. The C# structures have the following features
−
Structures can have methods, fields, indexers, properties, operator methods, and
events.
Structures can have defined constructors, but not destructors. However, you
cannot define a default constructor for a structure. The default constructor is
automatically defined and cannot be changed.
Unlike classes, structures cannot inherit other structures or classes.
Structures cannot be used as a base for other structures or classes.
A structure can implement one or more interfaces.
Structure members cannot be specified as abstract, virtual, or protected.
When you create a struct object using the New operator, it gets created and the
appropriate constructor is called. Unlike classes, structs can be instantiated
without using the New operator.
If the New operator is not used, the fields remain unassigned and the object cannot
be used until all the fields are initialized.
using System;
struct Books {
private string title;
private string author;
private string subject;
private int book_id;
/* book 2 specification */
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result −
Title : C Programming
Author : Nuha Ali
Subject : C Programming Tutorial
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700
# Inheritance
In C#, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or
modify the attributes and behaviors which is defined in other class.
In C#, the class which inherits the members of another class is called derived
class and the class whose members are inherited is called base class. The derived
class is the specialized class for the base class.
Advantage of C# Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is
no need to define the member again. So less code is required in the class.
1. using System;
2. public class Employee
3. {
4. public float salary = 40000;
5. }
6. public class Programmer: Employee
7. {
8. public float bonus = 10000;
9. }
10. class TestInheritance{
11. public static void Main(string[] args)
12. {
13. Programmer p1 = new Programmer();
14.
15. Console.WriteLine("Salary: " + p1.salary);
16. Console.WriteLine("Bonus: " + p1.bonus);
17.
18. }
19. }
Output:
Salary: 40000
Bonus: 10000
1. using System;
2. public class Animal
3. {
4. public void eat() { Console.WriteLine("Eating..."); }
5. }
6. public class Dog: Animal
7. {
8. public void bark() { Console.WriteLine("Barking..."); }
9. }
10. class TestInheritance2{
11. public static void Main(string[] args)
12. {
13. Dog d1 = new Dog();
14. d1.eat();
15. d1.bark();
16. }
17. }
Output:
Eating...
Barking...
1. using System;
2. public class Animal
3. {
4. public void eat() { Console.WriteLine("Eating..."); }
5. }
6. public class Dog: Animal
7. {
8. public void bark() { Console.WriteLine("Barking..."); }
9. }
10. public class BabyDog : Dog
11. {
12. public void weep() { Console.WriteLine("Weeping..."); }
13. }
14. class TestInheritance2{
15. public static void Main(string[] args)
16. {
17. BabyDog d1 = new BabyDog();
18. d1.eat();
19. d1.bark();
20. d1.weep();
21. }
22. }
Output:
Eating...
Barking...
Weeping...
Polymorphism
Polymorphism means “Many Forms”. In Polymorphism, poly means “Many” and
morph means “Forms.” Polymorphism is one of the main pillars in Object Oriented
Programming. It allows you to create multiple methods with the same name but
different signatures in the same class. The same name methods can also be in
derived classes.
1. Method Overloading
2. Method Overriding
Method Overloading
Method Overloading is a type of polymorphism. It has several names like “Compile Time
Polymorphism” or “Static Polymorphism” and sometimes it is called “Early Binding”.
Method Overloading means creating multiple methods in a class with same names but
different signatures (Parameters). It permits a class, struct, or interface to declare multiple
methods with the same name with unique signatures.
Compiler automatically calls required method to check number of parameters and their
type which are passed into that method.
o methods,
o constructors, and
In the above example, you can see that there are four methods with same name but type
of parameters or number of parameters is different. When you call Add(4,5), complier
automatically calls the method which has two integer parameters and when you call
Add(“hello”,”world”), complier calls the method which has two string parameters. So
basically in method overloading complier checks which method should be called at the
time of compilation.
C# Method Overloading Example: By changing no. of
arguments
Let's see the simple example of method overloading where we are changing number
of arguments of add() method.
1. using System;
2. public class Cal{
3. public static int add(int a,int b){
4. return a + b;
5. }
6. public static int add(int a, int b, int c)
7. {
8. return a + b + c;
9. }
10. }
11. public class TestMemberOverloading
12. {
13. public static void Main()
14. {
15. Console.WriteLine(Cal.add(12, 23));
16. Console.WriteLine(Cal.add(12, 23, 25));
17. }
18. }
Output:
35
60
C# Member Overloading Example: By changing data type
of arguments
Let's see the another example of method overloading where we are changing data
type of arguments.
1. using System;
2. public class Cal{
3. public static int add(int a, int b){
4. return a + b;
5. }
6. public static float add(float a, float b)
7. {
8. return a + b;
9. }
10. }
11. public class TestMemberOverloading
12. {
13. public static void Main()
14. {
15. Console.WriteLine(Cal.add(12, 23));
16. Console.WriteLine(Cal.add(12.4f,21.3f));
17. }
18. }
Output:
35
33.7
Method Overriding
Method Overriding is a type of polymorphism. It has several names like “Run Time
Polymorphism” or “Dynamic Polymorphism” and sometime it is called “Late Binding”.
Method Overriding means having two methods with same name and same signatures
[parameters], one should be in the base class and other method should be in a derived
class [child class]. You can override the functionality of a base class method to create a
same name method with same signature in a derived class. You can achieve method
overriding using inheritance. Virtual and Override keywords are used to achieve method
overriding. If we use Virtual keyword, then we tell to compiler that this method can be
overridden by the derived classes. If we use Overrride keyword, then we tell to the
compiler that this method is overriding the same named method in the base class.
Virtual Keyword
It tells the compiler that this method can be overridden by derived classes.
Override Keyword
In the subclass, it tells the compiler that this method is overriding the same named
method in the base class.
Base Keyword
In the subclass, it calls the base class method for overriding functionality.OR
This is used to access members of the base class from derived class.
Sr.
Method Overloading Method Overriding
No
Creating more than one method or Creating a method in the derived
function having same name but different class with the same signature as a
1.
signatures or the parameters in the same method in the base class is called as
class is called method overloading. method overriding
2. It is called the compile time polymorphism It is called runtime polymorphism
It must have same method name as
It has the same method name but with
3. well as the signatures or the
different signatures or the parameters
parameters.
Method overloading doesn’t need
4. Mehod overriding needs inheritance
inheritance
Method overriding needs hierachy
Method overloading is possible in single
5. level of the classes i.e. one parent
class only
class and other child class.
6. Access modifier can be any Access modifier must be public.
Method overloading is also called early Method overriding is also called late
7.
binding. binding.
using System;
class baseClass
Console.WriteLine("Base class");
// overriding
Console.WriteLine("Derived class");
class GFG {
// Main Method
// class 'baseClass'
// of class 'baseClass'
obj.show();
obj.show();
Output:
Base class
Base class
Explanation: In this program, the object obj invokes class baseClass two times
and call the method show() of class baseClass. To avoid this problem we use
virtual and override keyword.
Example 2: Method overriding using virtual and override modifiers.
// C# program to illustrate the use of
using System;
class baseClass {
Console.WriteLine("Base class");
// class 'derived'
Console.WriteLine("Derived class");
class GFG {
// Main Method
baseClass obj;
// of class 'baseClass'
// it invokes 'show()'
// of class 'baseClass'
obj.show();
obj.show();
OutPut:
Base class
Derived class
Dynamic Type in C#
In C# 4.0, a new type is introduced that is known as a dynamic type. It is used
to avoid the compile-time type checking. The compiler does not check the type
of the dynamic type variable at compile time, instead of this, the compiler gets
the type at the run time. The dynamic type variable is created using dynamic
keyword.
Example:
dynamic value = 123;
Important Points:
In most of the cases, the dynamic type behaves like object types.
You can get the actual type of the dynamic variable at runtime by
using GetType() method. The dynamic type changes its type at the run time
based on the value present on the right-hand side. As shown in the below
example.
Example:
using System;
class GFG {
// Main Method
// Dynamic variables
dynamic value1 = "GeeksforGeeks";
// dynamic variables
value1.GetType().ToString());
value2.GetType().ToString());
value3.GetType().ToString());
value4.GetType().ToString());
}
}
Output:
Example 2:
using System;
class GFG {
Console.WriteLine(s1 + s2);
}
// Main method
addstr("G", "G");
addstr("Geeks", "forGeeks");
addstr("Cat", "Dog");
addstr("Hello", 1232);
addstr(12, 30);
Output:
GG
GeeksforGeeks
CatDog
Hello1232
42
Assignments: Array and Array List