0% found this document useful (0 votes)
54 views

CSharp MidTerm

C# is an object-oriented programming language that was developed by Microsoft to be used with its .NET framework. It can be used to create various applications including Windows apps, web apps, and web services. The document discusses the features of C# like garbage collection and generics. It also explains how to set up an development environment to write and run C# programs using Visual Studio or other IDEs. A simple "Hello World" program is presented to demonstrate the basic structure of a C# program, including namespaces, classes, and methods.

Uploaded by

Muhammad Bilal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

CSharp MidTerm

C# is an object-oriented programming language that was developed by Microsoft to be used with its .NET framework. It can be used to create various applications including Windows apps, web apps, and web services. The document discusses the features of C# like garbage collection and generics. It also explains how to set up an development environment to write and run C# programs using Visual Studio or other IDEs. A simple "Hello World" program is presented to demonstrate the basic structure of a C# program, including namespaces, classes, and methods.

Uploaded by

Muhammad Bilal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

C# is a modern, general-purpose, object-oriented programming language developed by

Microsoft and approved by European Computer Manufacturers Association (ECMA) and


International Standards Organization (ISO).
C# was developed by Anders Hejlsberg and his team during the development of .Net
Framework.
C# is designed for Common Language Infrastructure (CLI), which consists of the
executable code and runtime environment that allows use of various high-level
languages on different computer platforms and architectures.
The following reasons make C# a widely used professional language −

 It is a modern, general-purpose programming language


 It is object oriented.
 It is component oriented.
 It is easy to learn.
 It is a structured language.
 It produces efficient programs.
 It can be compiled on a variety of computer platforms.
 It is a part of .Net Framework.

Strong Programming Features of C#


Although C# constructs closely follow traditional high-level languages, C and C++ and
being an object-oriented programming language. It has strong resemblance with Java, it
has numerous strong programming features that make it endearing to a number of
programmers worldwide.
Following is the list of few important features of C# −

 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.

The .Net Framework


The .Net framework is a revolutionary platform that helps you to write the following types
of applications −

 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 −

 Common Language Runtime (CLR)


 The .Net Framework Class Library
 Common Language Specification
 Common Type System
 Metadata and Assemblies
 Windows Forms
 ASP.Net and ASP.Net AJAX
 ADO.Net
 Windows Workflow Foundation (WF)
 Windows Presentation Foundation
 Windows Communication Foundation (WCF)
 LINQ
For the jobs each of these components perform, please see ASP.Net - Introduction, and
for details of each component, please consult Microsoft's documentation.

Integrated Development Environment (IDE) for C#


Microsoft provides the following development tools for C# programming −

 Visual Studio 2010 (VS)


 Visual C# 2010 Express (VCE)
 Visual Web Developer
The last two are freely available from Microsoft official website. Using these tools, you
can write all kinds of C# programs from simple command-line applications to more
complex applications. You can also write C# source code files using a basic text editor,
like Notepad, and compile the code into assemblies using the command-line compiler,
which is again a part of the .NET Framework.
Visual C# Express and Visual Web Developer Express edition are trimmed down
versions of Visual Studio and has the same appearance. They retain most features of
Visual Studio. In this tutorial, we have used Visual C# 2010 Express.
You can download it from Microsoft Visual Studio. It gets installed automatically on your
machine.
Note: You need an active internet connection for installing the express edition.

Writing C# Programs on Linux or Mac OS


Although the.NET Framework runs on the Windows operating system, there are some
alternative versions that work on other operating systems. Mono is an open-source
version of the .NET Framework which includes a C# compiler and runs on several
operating systems, including various flavors of Linux and Mac OS. Kindly check Go
Mono.
The stated purpose of Mono is not only to be able to run Microsoft .NET applications
cross-platform, but also to bring better development tools for Linux developers. Mono
can be run on many operating systems including Android, BSD, iOS, Linux, OS X,
Windows, Solaris, and UNIX.
Before we study basic building blocks of the C# programming language, let us look at a
bare minimum C# program structure so that we can take it as a reference in upcoming
chapters.

Creating Hello World Program


A C# program consists of the following parts −

 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 the namespace declaration. A namespace is a collection of


classes. The HelloWorldApplication namespace contains the class HelloWorld.
Note: namespace is designed for providing a way to keep one set of names
separate from another. The class names declared in one namespace does not
conflict with the same class names declared in another.

 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.

Compiling and Executing the Program


If you are using Visual Studio.Net for compiling and executing C# programs, take the
following steps −
 Start Visual Studio.
 On the menu bar, choose File -> New -> Project.
 Choose Visual C# from templates, and then choose Windows.
 Choose Console Application.
 Specify a name for your project and click OK button.
 This creates a new project in Solution Explorer.
 Write code in the Code Editor.
 Click the Run button or press F5 key to execute the project. A Command Prompt
window appears that contains the line Hello World.
You can compile a C# program by using the command-line instead of the Visual Studio
IDE −
 Open a text editor and add the above-mentioned code.
 Save the file as helloworld.cs
 Open the command prompt tool and go to the directory where you saved the file.
 Type csc helloworld.cs and press enter to compile your code.
 If there are no errors in your code, the command prompt takes you to the next line
and generates helloworld.exe executable file.
 Type helloworld to execute your program.
 You can see the output Hello World printed on the screen.

Namespace Example (Try to understand)


 using System;
 using first_space;
 using second_space;

 namespace first_space {
 class abc {
 public void func() {
 Console.WriteLine("Inside first_space");
 }
 }
 }
 namespace second_space {
 class efg {
 public void func() {
 Console.WriteLine("Inside second_space");
 }
 }
 }
 class TestClass {
 static void Main(string[] args) {
 abc fc = new abc();
 efg sc = new efg();
 fc.func();
 sc.func();
 Console.ReadKey();
 }
 }
 When the above code is compiled and executed, it produces the following result

 Inside first_space
 Inside second_space

C# Command Line Arguments
Arguments that are passed by command line known as command line arguments. We
can send arguments to the Main method while executing the code. The
string args variable contains all the values passed from the command line.

In the following example, we are passing command line arguments during execution of
program.

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?

After executing the code, it produces the following output to the console.

Output:

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

C# Basic Syntax (Example)


C# is an object-oriented programming language. In Object-Oriented Programming methodology,
a program consists of various objects that interact with each other by means of actions. The
actions that an object may take are called methods. Objects of the same kind are said to have the
same type or, are said to be in the same class.
For example, let us consider a Rectangle object. It has attributes such as length and width.
Depending upon the design, it may need ways for accepting the values of these attributes,
calculating the area, and displaying details.
Let us look at implementation of a Rectangle class and discuss C# basic syntax −

Live Demo
using System;

namespace RectangleApplication {
class Rectangle {

// member variables
double length;
double width;

public void Acceptdetails() {


length = 4.5;
width = 3.5;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 3.5
Area: 15.75

The using Keyword


The first statement in any C# program is
using System;
The using keyword is used for including the namespaces in the program. A program can include
multiple using statements.

The class Keyword


The class keyword is used for declaring a class.

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

abstract as base bool break byte case

catch char checked class const continue decimal

default delegate do double else enum event

explicit extern false finally fixed float for

foreach goto if implicit in in (generic int


modifier)

interface internal is lock long namespace new

null object operator out out (generic override params


modifier)
private protected public readonly ref return sbyte

sealed short sizeof stackalloc static string struct

switch this throw true try typeof uint

ulong unchecked unsafe ushort using virtual void

volatile while

Contextual Keywords

add alias ascending descending dynamic from get

global group into join let orderby partial


(type)

partial remove select set


(method)

Decimal to Binary Conversion Algorithm


Step 1: Divide the number by 2 through % (modulus operator) and store the
remainder in array

Step 2: Divide the number by 2 through / (division operator)

Step 3: Repeat the step 2 until the number is greater than zero

Let's see the C# example to convert decimal to binary.

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

C# Nested For Loop


In C#, we can use for loop inside another for loop, it is known as nested for loop. The
inner loop is executed fully when outer loop is executed one time. So if outer loop and
inner loop are executed 3 times, inner loop will be executed 3 times for each outer loop
i.e. total 9 times.

Let's see a simple example of nested for loop in C#.

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


If we use double semicolon in for loop, it will be executed infinite times. Let's see a
simple example of infinite for loop in C#.

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. }

C# While Loop Example


Let's see a simple example of while loop to print table of 1.
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# do-while Loop Example


Let's see a simple example of C# do-while loop to print the table of 1.

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.

C# Break Statement Example


Let's see a simple example of C# break statement which is used inside the 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.

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
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.

C# Goto Statement Example


Let's see the simple example of goto statement in C#.

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# Function
Function is a block of code that has a signature. Function is used to execute statements
specified in the code block. A function consists of the following components:

Function name: It is a unique name that is used to make Function call.

Return type: It is used to specify the data type of function return value.

Body: It is a block that contains executable statements.

Access specifier: It is used to specify function accessibility in the application.

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. }

Access-specifier, parameters and return statement are optional.

Let's see an example in which we have created a function that returns a string value
and takes a string parameter.

C# Function: using no parameter and return type


A function that does not return any value specifies void type as a return type. In the
following example, a function is created without 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. namespace FunctionExample
3. {
4. class Program
5. {
6. // User defined function without return type
7. public void Show(string message)
8. {
9. Console.WriteLine("Hello " + message);
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("Rahul Kumar"); // Calling Function
17. }
18. }
19. }

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.

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 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:

Value before calling the function 50


Value inside the show function 2500
Value after calling the function 2500
C# Arrays
Like other programming languages, array in C# is a group of similar types of elements
that have contiguous memory location. In C#, array is an object of base
type System.Array. In C#, array index starts from 0. We can store only fixed set of
elements in C# array.

Advantages of C# Array
o Code Optimization (less code)

o Random Access

o Easy to traverse data

o Easy to manipulate data

o Easy to sort data etc.

Disadvantages of C# Array
o Fixed size

C# Array Types
There are 3 types of arrays in C# programming:

1. Single Dimensional Array

2. Multidimensional Array

3. Jagged Array
C# Single Dimensional Array
To create single dimensional array, you need to use square brackets [] after the type.

1. int[] arr = new int[5];//creating array

You cannot place square brackets after the identifier.

1. int arr[] = new int[5];//compile time error

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.

1. int[] arr = new int[5]{ 10, 20, 30, 40, 50 };

We can omit the size of array.

1. int[] arr = new int[]{ 10, 20, 30, 40, 50 };

We can omit the new operator also.

1. int[] arr = { 10, 20, 30, 40, 50 };

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:

Minimum element is: 10


Minimum element is: 11
C# Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#. It can be two
dimensional or three dimensional. The data is stored in tabular form (row * column)
which is also known as matrix.

To create multidimensional array, we need to use comma inside the square brackets.
For example:

1. int[,] arr=new int[3,3];//declaration of 2D array


2. int[,,] arr=new int[3,3,3];//declaration of 3D array
C# Multidimensional Array Example
Let's see a simple example of multidimensional array in C# which declares, initializes
and traverse two dimensional array.

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 = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

We can omit the array size.

1. int[,] arr = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

We can omit the new operator also.

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

What is ArrayList in C#?


The ArrayList collection is similar to the Arrays data type in C#. The biggest
difference is the dynamic nature of the array list collection.

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.

Declaration of an Array List


The declaration of an ArrayList is provided below. An array list is created with
the help of the ArrayList Datatype. The "new" keyword is used to create an
object of an ArrayList. The object is then assigned to the variable a1. So now
the variable a1 will be used to access the different elements of the array list.

ArrayList a1 = new ArrayList()


Adding elements to an array
he add method is used to add an element to the ArrayList. The add method
can be used to add any sort of data type element to the array list. So you can
add an Integer, or a string, or even a Boolean value to the array list. The
general syntax of the addition method is given below:
ArrayList.add(element)

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;

// Accessing & Assigning 47 to the first element ([0]) of the fourth


array ([3]):
jagged_arr[3][0] = 47;
Program:

// C# program to illustrate the declaration

// and Initialization of Jagged Arrays

using System;

class GFG {

// Main Method

public static void Main()

// Declare the Jagged Array of four elements:

int[][] jagged_arr = new int[4][];

// Initialize the elements

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};


// Display the array elements:

for (int n = 0; n < jagged_arr.Length; n++) {

// Print the row number

System.Console.Write("Row({0}): ", n);

for (int k = 0; k < jagged_arr[n].Length; k++) {

// Print the elements in the row

System.Console.Write("{0} ", jagged_arr[n][k]);

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 a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through
object.

Let's see an example to create object using new keyword.

1. Student s1 = new Student();//creating an object of Student

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.

Let's see an example of C# class that has two fields only.

1. public class Student


2. {
3. int id;//field or data member
4. String name;//field or data member
5. }

C# Object and Class Example


Let's see an example of class that has two fields: id and name. It creates instance of
the class, initializes the object and prints the object value.

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:

101 Sonoo 890000


102 Mahesh 490000

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.

There can be two types of constructors in C#.

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.

C# Default Constructor Example: Having Main() within class


1. using System;
2. public class Employee
3. {
4. public Employee()
5. {
6. Console.WriteLine("Default Constructor Invoked");
7. }
8. public static void Main(string[] args)
9. {
10. Employee e1 = new Employee();
11. Employee e2 = new Employee();
12. }
13. }

Output:

Default Constructor Invoked


Default Constructor Invoked
C# Default Constructor Example: Having Main() in another
class
Let's see another example of default constructor where we are having Main() method in
another class.

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:

Default Constructor Invoked


Default Constructor Invoked

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:

101 Sonoo 890000


102 Mahesh 490000
C# Destructor
A destructor works opposite to constructor, It destructs the objects of classes. It can be
defined only once in a class. Like constructors, it is invoked automatically.

Note: C# destructor cannot have parameters. Moreover, modifiers can't be applied on


destructors.
C# Constructor and Destructor Example
Let's see an example of constructor and destructor in C# which is called automatically.

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#.

o It can be used to refer current class instance variable. It is used if field


names (instance variables) and parameter names are same, that is why both can
be distinguish easily.

o It can be used to pass current object as a parameter to another method.

o It can be used to declare indexers.

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:

101 Sonoo 890000


102 Mahesh 490000

We will learn about other usage of this keyword in next chapters.

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.

Note: Indexers and destructors cannot be static.


Advantage of C# static keyword
Memory efficient: Now we don't need to create instance for accessing the static
members, so it saves memory. Moreover, it belongs to the type, so it will not get
memory each time when instance is created.

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.

C# static field example


Let's see the simple example of static field in C#.

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:

101 Sonoo 8.8


102 Mahesh 8.8
C# static field example 2: changing static field
If you change the value of static field, it will be applied to all the objects.

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:

101 Sonoo 10.5


102 Mahesh 10.5
C# static field example 3: Counting Objects
Let's see another example of static keyword in C# which counts the objects.

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.

Points to remember for C# static class


o C# static class contains only static members.

o C# static class cannot be instantiated.

o C# static class is sealed.

o C# static class cannot contain instance constructors.

C# static class example


Let's see the example of static class that contains static field and static method.

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:

Value of PI is: 3.14


Cube of 3 is: 27
C# static constructor
C# static constructor is used to initialize static fields. It can also be used to perform any
action that is to be performed only once. It is invoked automatically before first
instance is created or any static member is referenced.

Points to remember for C# Static Constructor


o C# static constructor cannot have any modifier or parameter.

o C# static constructor is invoked implicitly. It can't be called explicitly.

C# Static Constructor example


Let's see the example of static constructor which initializes the static field
rateOfInterest in Account class.

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:

101 Sonoo 9.5


102 Mahesh 9.5
C# Structs
Structures are used to represent a record. Suppose you want to keep track of your books
in a library. You might want to track the following attributes about each book −

 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;
};

public class testStructure {


public static void Main(string[] args) {
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
Book1.title = "C 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;

/* print Book1 info */


Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);

/* print Book2 info */


Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);

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.

Class versus Structure


Classes and Structures have the following basic differences −

 classes are reference types and structs are value types


 structures do not support inheritance
 structures cannot have default constructor
In the light of the above discussions, let us rewrite the previous example −
Live Demo

using System;

struct Books {
private string title;
private string author;
private string subject;
private int book_id;

public void getValues(string t, string a, string s, int id) {


title = t;
author = a;
subject = s;
book_id = id;
}

public void display() {


Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};

public class testStructure {

public static void Main(string[] args) {


Books Book1 = new Books(); /* Declare Book1 of type Book */
Books Book2 = new Books(); /* Declare Book2 of type Book */
/* book 1 specification */
Book1.getValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);

/* book 2 specification */
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);

/* print Book1 info */


Book1.display();

/* print Book2 info */


Book2.display();

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.

C# Single Level Inheritance Example: Inheriting Fields


When one class inherits another class, it is known as single level inheritance. Let's see
the example of single level inheritance which inherits the fields only.

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

In the above example, Employee is the base class and Programmer is


the derived class.

C# Single Level Inheritance Example: Inheriting


Methods
Let's see another example of inheritance in C# which inherits methods only.

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...

C# Multi Level Inheritance Example


When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C#. Inheritance is transitive so the last derived class
acquires all the members of all its base classes.

Let's see the example of multi level inheritance in C#.

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.

There are two types of Polymorphism,

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.

In C#, we can overload:

o methods,

o constructors, and

The advantage of method overloading is that it increases the readability of the


program because you don't need to use different names for same action.

You can perform method overloading in C# by two ways:

1. By changing number of arguments

2. By changing data type of the arguments


1. using System;
2. namespace DemoCsharp
3. {
4. class Program
5. {
6. public int Add(int num1, int num2)
7. {
8. return (num1 + num2);
9. }
10. public int Add(int num1, int num2, int num3)
11. {
12. return (num1 + num2 + num3);
13. }
14. public float Add(float num1, float num2)
15. {
16. return (num1 + num2);
17. }
18. public string Add(string value1, string value2)
19. {
20. return (value1 + " " + value2);
21. }
22. static void Main(string[] args)
23. {
24. Program objProgram = new Program();
25. Console.WriteLine("Add with two int parameter
:" + objProgram.Add(3, 2));
26. Console.WriteLine("Add with three int paramete
r :" + objProgram.Add(3, 2, 8));
27. Console.WriteLine("Add with two float paramete
r :" + objProgram.Add(3 f, 22 f));
28. Console.WriteLine("Add with two string paramet
er :" + objProgram.Add("hello", "world"));
29. Console.ReadLine();

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.

Example 1: Method Overriding without using virtual and override modifiers


C#
Output:
Base class
Base class
// C# program to demonstrate the method overriding

// without using 'virtual' and 'override' modifiers

using System;

// base class name 'baseClass'

class baseClass

public void show()

Console.WriteLine("Base class");

// derived class name 'derived'

// 'baseClass' inherit here

class derived : baseClass

// overriding

new public void show()

Console.WriteLine("Derived class");

class GFG {
// Main Method

public static void Main()

// 'obj' is the object of

// class 'baseClass'

baseClass obj = new baseClass();

// invokes the method 'show()'

// of class 'baseClass'

obj.show();

obj = new derived();

// it also invokes the method

// 'show()' of class 'baseClass'

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

//'virtual' and 'override' modifiers

using System;

class baseClass {

// show() is 'virtual' here

public virtual void show()

Console.WriteLine("Base class");

// class 'baseClass' inherit

// class 'derived'

class derived : baseClass

//'show()' is 'override' here

public override void show()

Console.WriteLine("Derived class");

class GFG {
// Main Method

public static void Main()

baseClass obj;

// 'obj' is the object

// of class 'baseClass'

obj = new baseClass();

// it invokes 'show()'

// of class 'baseClass'

obj.show();

// the same object 'obj' is now

// the object of class 'derived'

obj = new derived();

// it invokes 'show()' of class 'derived'

// 'show()' of class 'derived' is overridden

// for 'override' modifier

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:

// C# program to illustrate how to get the

// actual type of the dynamic type variable

using System;

class GFG {

// Main Method

static public void Main()

// Dynamic variables
dynamic value1 = "GeeksforGeeks";

dynamic value2 = 123234;

dynamic value3 = 2132.55;

dynamic value4 = false;

// Get the actual type of

// dynamic variables

// Using GetType() method

Console.WriteLine("Get the actual type of value1: {0}",

value1.GetType().ToString());

Console.WriteLine("Get the actual type of value2: {0}",

value2.GetType().ToString());

Console.WriteLine("Get the actual type of value3: {0}",

value3.GetType().ToString());

Console.WriteLine("Get the actual type of value4: {0}",

value4.GetType().ToString());

}
}

Output:

Get the actual type of value1: System.String


Get the actual type of value2: System.Int32
Get the actual type of value3: System.Double
Get the actual type of value4: System.Boolean

Example 2:

// C# program to illustrate how to pass

// dynamic type parameters in the method

using System;

class GFG {

// Method which contains dynamic parameters

public static void addstr(dynamic s1, dynamic s2)

Console.WriteLine(s1 + s2);

}
// Main method

static public void Main()

// Calling addstr 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

You might also like