KEMBAR78
Unit - 1 Introduction | PDF | Programming | Constructor (Object Oriented Programming)
0% found this document useful (0 votes)
40 views60 pages

Unit - 1 Introduction

C# is a general-purpose, object-oriented programming language developed by Microsoft for creating a variety of applications on the .NET Framework. The .NET Framework provides a robust environment for application development, consisting of the Common Language Runtime (CLR) and the Framework Class Library (FCL). Key features of C# include its modern design, ease of learning, and support for encapsulation, inheritance, and polymorphism.

Uploaded by

Dipsan Kadariya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views60 pages

Unit - 1 Introduction

C# is a general-purpose, object-oriented programming language developed by Microsoft for creating a variety of applications on the .NET Framework. The .NET Framework provides a robust environment for application development, consisting of the Common Language Runtime (CLR) and the Framework Class Library (FCL). Key features of C# include its modern design, ease of learning, and support for encapsulation, inheritance, and polymorphism.

Uploaded by

Dipsan Kadariya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Introduction to C# Language

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


Anders Hejlsberg and his team during the development of .Net Framework. It can be used
to create desktop, web and mobile applications.
C# is a hybrid of C and C++; it is a Microsoft programming language developed to compete
with Sun's Java language. C# is an object-oriented programming language used with XML-
based Web services on the .NET platform and designed for improving productivity in the
development of Web applications.
C# is an elegant and type-safe object-oriented language that enables developers to build a
variety of secure and robust applications that run on the .NET Framework. You can use C# to
create Windows client applications, XML Web services, distributed components, client-server
applications, database applications, and much, much more. Visual C# provides an advanced
code editor, convenient user interface designers, integrated debugger, and many other tools
to make it easier to develop applications based on the C# language and the .NET Framework.
As an object-oriented language, C# supports the concepts of encapsulation, inheritance, and
polymorphism. All variables and methods, including the Main method, the application's entry
point, are encapsulated within class definitions.

The following reasons make C# a widely used professional language (Features of C#):
1. It is a modern, general-purpose programming language
2. It is object oriented.
3. It is component oriented.
4. It is easy to learn.
5. It is a structured language.
6. It produces efficient programs.
7. It can be compiled on a variety of computer platforms.
8. It is a part of .Net Framework.

Introduction and Overview of .Net Framework


.NET is the framework for which we develop applications. It sits in between our application
programs and operating system.
.NET provides an object oriented environment. It ensures safe execution of the code by
performing required runtime validations. For example, it is never possible to access an
element of an array outside the boundary. Similarly, it is not possible to a program to write
into another programs area, etc. The runtime validations performed by .NET makes the entire
environment robust.
It is a programming infrastructure created by Microsoft for building, deploying, and running
applications and services that use .NET technologies, such as desktop applications and Web
services.
The .NET Framework consists of:
- the Common Language Runtime
- the Framework Class Library

Prepared By: Raju Poudel [Lecturer - MMC] 1


Common Language Runtime(CLR):
CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-time
environment in the .NET Framework that runs the codes and helps in making the
development process easier by providing the various services such as remoting, thread
management, type-safety, memory management, robustness etc. Basically, it is responsible
for managing the execution of .NET programs regardless of any .NET programming language.
It also helps in the management of code, as code that targets the runtime is known as the
Managed Code and code doesn’t target to runtime is known as Unmanaged code.

Features of Common Language Runtime:


1. The runtime enforces code access security. For example, users can trust that an
executable embedded in a Web page can play an animation on screen or sing a song,
but cannot access their personal data, file system, or network.
2. The runtime also enforces code robustness by implementing a strict type-and-code-
verification infrastructure called the common type system (CTS). The CTS ensures that
all managed code is self-describing.

Prepared By: Raju Poudel [Lecturer - MMC] 2


3. The runtime also accelerates developer productivity. For example, programmers can
write applications in their development language of choice, yet take full advantage of
the runtime, the class library, and components written in other languages by other
developers. Any compiler vendor who chooses to target the runtime can do so.
Language compilers that target the .NET Framework make the features of the .NET
Framework available to existing code written in that language, greatly easing the
migration process for existing applications.
4. While the runtime is designed for the software of the future, it also supports software
of today and yesterday.
5. The runtime is designed to enhance performance.
6. The runtime can be hosted by high-performance, server-side applications, such as
Microsoft SQL Server and Internet Information Services (IIS).

Framework Class Library (FCL):


The class library is a comprehensive, object-oriented collection of reusable types that you can
use to develop applications ranging from traditional command-line or graphical user interface
(GUI) applications to applications based on the latest innovations provided by ASP.NET, such
as Web Forms and XML Web services.
It is the collection of reusable, object-oriented class libraries and methods etc. that can be
integrated with CLR. Also called the Assemblies. It is just like the header files in C/C++ and
packages in the java. Installing .NET framework basically is the installation of CLR and FCL into
the system.

The core libraries are sometimes collectively called the Base Class Library (BCL). The entire
framework is called the Framework Class Library (FCL).

Features of Framework Class Library:


An object-oriented class library, the .NET Framework types enable you to accomplish a range
of common programming tasks, including tasks such as string management, data collection,
database connectivity, and file access. In addition to these common tasks, the class library
includes types that support a variety of specialized development scenarios. For example, you
can use the .NET Framework to develop the following types of applications and services:
1. Console applications
2. Windows GUI applications (Windows Forms).
3. Windows Presentation Foundation (WPF) applications.
4. ASP.NET applications.
5. Windows services.
6. Service-oriented applications using Windows Communication Foundation (WCF).
7. Workflow-enabled applications using Windows Workflow Foundation (WF).

Prepared By: Raju Poudel [Lecturer - MMC] 3


Other Frameworks
The Microsoft .NET Framework is the most expansive and mature framework, but runs only
on Microsoft Windows (desktop/server). Over the years, other frame- works have emerged
to support other platforms. There are currently three major players besides the .NET
Framework, all of which are currently owned by Microsoft:

Universal Windows Platform (UWP)


For writing Windows 10 Store Apps and for targeting Windows 10 devices (mobile, XBox,
Surface Hub, Hololens). Your app runs in a sandbox to lessen the threat of malware,
prohibiting operations such as reading or writing arbitrary files.

.NET Core with ASP.NET Core


An open source framework (originally based on a cut-down version of the .NET Framework)
for writing easily deployable Internet apps and micro services that run on Windows, macOS,
and Linux. Unlike the .NET Frame- work, .NET Core can be packaged with the web application
and xcopy deployed (self-contained deployment).

Xamarin
For writing mobile apps that target iOS, Android, and Windows Mobile. The Xamarin company
was purchased by Microsoft in 2016.

Table 1-1 compares the current platform support for each of the major frameworks

Prepared By: Raju Poudel [Lecturer - MMC] 4


Compiling and executing C# program:
Setting up the environment
Step 1: Go to Control Panel -> System and Security -> System. Under Advanced System
Setting option click on Environment Variables as shown below:

Step 2: Now, we have to alter the “Path” variable under System variables so that it also
contains the path to the .NET Framework environment. Select the “Path” variable and click
on the Edit button as shown below:

Prepared By: Raju Poudel [Lecturer - MMC] 5


Step 3: We will see a list of different paths, click on the New button and then add the path
where .NET Framework is installed.

Prepared By: Raju Poudel [Lecturer - MMC] 6


Compiling & Running a Program

Step 1: Open the text editor like Notepad or Notepad++, and write the code that you want to
execute. Now save the file with .cs extension.

Step 2: Compile your C# source code with the use of command:


csc File_name.cs

If your program has no error then it will create a filename.exe file in the same directory where you
have saved your program. Suppose you saved the above program as Hello.cs. So you will write csc
Hello.cs on cmd. This will create a Hello.exe file.

Step 3: Now there are two ways to execute the Hello.exe.


• First, you have to simply type the filename i.e Hello on the cmd and it will give the
output.
• Second, you can go to the directory where you saved your program and there you find
filename.exe. You have to simply double-click that file and it will give the output.

Constructors
A constructor in C# is a block of code similar to a method that’s called when an instance of an
object is created. Here are the key differences between a constructor and a method:
• A constructor doesn’t have a return type.
• The name of the constructor must be the same as the name of the class.
• Unlike methods, constructors are not considered members of a class.
• A constructor is called automatically when a new instance of an object is created.

All classes have constructors, whether you define one or not, because C# automatically
provides a default constructor that initializes all member variables to zero. However, once
you define your own constructor, the default constructor is no longer used.

Default Constructor
The default constructor is a constructor that is automatically generated in the absence of
explicit constructors (i.e. no user defined constructor). The automatically provided
constructor is called sometimes a nullary constructor.
Following is the syntax of a default constructor –

Instance Constructors
Constructors run initialization code on a class or struct. A constructor is defined like a method,
except that the method name and return type are reduced to the name of the enclosing type:

Prepared By: Raju Poudel [Lecturer - MMC] 7


Instance constructors allow the following modifiers:
public internal private protected

Overloaded Constructors
A class or struct may overload constructors. To avoid code duplication, one constructor may
call another, using this keyword:

When one constructor calls another, the called constructor executes first.

Destructor
Destructors in C# are methods inside the class used to destroy instances of that class when
they are no longer needed. The Destructor is called implicitly by the .NET Framework’s
Garbage collector and therefore programmer has no control as when to invoke the
destructor. An instance variable or an object is eligible for destruction when it is no longer
reachable.
Important Points:
• A Destructor is unique to its class i.e. there cannot be more than one destructor in a
class.
• A Destructor has no return type and has exactly the same name as the class name
(Including the same case).
• It is distinguished apart from a constructor because of the Tilde symbol (~) prefixed to
its name.
• A Destructor does not accept any parameters and modifiers.
• It cannot be defined in Structures. It is only used with classes.
• It cannot be overloaded or inherited.
• It is called when the program exits.
• Internally, Destructor called the Finalize method on the base class of object.

Prepared By: Raju Poudel [Lecturer - MMC] 8


Syntax

Example:
class ConsDes
{
//constructor
public ConsDes(string message)
{
Console.WriteLine(message);
}

public void test()


{
Console.WriteLine("This is a method");
}

//destructor
~ConsDes()
{
Console.WriteLine("This is a destructor");
Console.ReadKey();
}
}

class Construct
{
static void Main(string[] args)
{
string msg = "This is a constructor";
ConsDes obj = new ConsDes(msg);
obj.test();
}
}

Prepared By: Raju Poudel [Lecturer - MMC] 9


Output:
This is a constructor
This is a method
This is a destructor

Static Constructor
In c#, Static Constructor is used to perform a particular action only once throughout the
application. If we declare a constructor as static, then it will be invoked only once irrespective
of number of class instances and it will be called automatically before the first instance is
created.
Generally, in c# the static constructor will not accept any access modifiers and parameters. In
simple words we can say it’s a parameter less.

Following are the properties of static constructor in c# programming language.


• Static constructor in c# won’t accept any parameters and access modifiers.
• The static constructor will invoke automatically, whenever we create a first instance
of class.
• The static constructor will be invoked by CLR so we don’t have a control on static
constructor execution order in c#.
• In c#, only one static constructor is allowed to create.

C# Static Constructor Syntax


class User
{
// Static Constructor
static User()
{
// Your Custom Code
}
}

Example
class User
{
// Static Constructor
static User()
{
Console.WriteLine("I am Static Constructor");
}
// Default Constructor
public User()
{
Console.WriteLine("I am Default Constructor");
}
}
class Program
{
static void Main(string[] args)
{

Prepared By: Raju Poudel [Lecturer - MMC] 10


// Both Static and Default constructors will invoke for first
instance
User user = new User();
// Only Default constructor will invoke
User user1 = new User();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}

Copy Constructor
A constructor that creates an object by copying variables from another object or that copies
the data of one object into another object is termed as the Copy Constructor. It is a
parameterized constructor that contains a parameter of the same class type. The main use of
copy constructor is to initialize a new instance to the values of an existing instance. Normally,
C# does not provide a copy constructor for objects, but if you want to create a copy
constructor in your program you can create according to your requirement.

Example:

using System;
class A{
private int a,b,sum;

public A(int x,int y){


a=x;
b=y;
}

//copy consturctor
public A(A obj){
sum=obj.a+obj.b;

//method
public void Display(){
Console.WriteLine("Sum={0}",sum);
}

Prepared By: Raju Poudel [Lecturer - MMC] 11


public class Program
{
public static void Main()
{
A obj1=new A(10,20);
A obj2=new A(obj1);
obj2.Display();
}
}

Output:
Sum=30

Properties in C#
Properties look like fields from the outside, but internally they contain logic, like methods
do. Properties are named members of classes, structures, and interfaces. Member variables
or methods in a class or structures are called Fields. Properties are an extension of fields and
are accessed using the same syntax. They use accessors(get and set) through which the
values of the private fields can be read, written or manipulated.

Usually, inside a class, we declare a data field as private and will provide a set of public SET
and GET methods to access the data fields. This is a good programming practice since the data
fields are not directly accessible outside the class. We must use the set/get methods to access
the data fields.
An example, which uses a set of set/get methods, is shown below.

Output:
10

Prepared By: Raju Poudel [Lecturer - MMC] 12


Automatic Properties
he most common implementation for a property is a getter and/or setter that simply reads
and writes to a private field of the same type as the property. An automatic property
declaration instructs the compiler to provide this implementation. We can improve the first
example in this section by declaring CurrentPrice as an automatic property:

Example of Properties:

class Chk
{
public int a { get;set;}
public int b { get; set; }
public int sum
{
get { return a + b; }
}

class Test
{
static void Main()
{
Chk obj = new Chk();
obj.a = 10;
obj.b = 5;
Console.WriteLine("Sum of "+obj.a+" and "+obj.b+" =
"+obj.sum);
Console.ReadKey();
}
}

Output:
Sum of 10 and 5 = 15

Prepared By: Raju Poudel [Lecturer - MMC] 13


Example - 2
using System;
class A{
private int a;
public int x{
set{a=value;}
get{return a+5;}
}
}

public class Program


{
public static void Main()
{
A obj=new A();
obj.x=10;
Console.WriteLine(obj.x);
}
}

Output:
15

Arrays
An array represents a fixed number of variables (called elements) of a particular type. The
elements in an array are always stored in a contiguous block of memory, providing highly
efficient access.
An array is denoted with square brackets after the element type. For example:

Square brackets also index the array, accessing a particular element by position:

This prints “e” because array indexes start at 0. We can use a for loop statement to iterate
through each element in the array. The for loop in this example cycles the integer i from 0 to
4:

An array initialization expression lets you declare and populate an array in a single step:

Prepared By: Raju Poudel [Lecturer - MMC] 14


Multidimensional Arrays
Multidimensional arrays come in two varieties: rectangular and jagged.
Rectangular arrays represent an n-dimensional block of memory, and jagged arrays are arrays
of arrays.

Rectangular arrays
Rectangular arrays are declared using commas to separate each dimension. The following
declares a rectangular two-dimensional array, where the dimensions are 3 by 3:

A rectangular array can be initialized as follows (to create an array identical to the previous
example):

Example Program,

Prepared By: Raju Poudel [Lecturer - MMC] 15


Jagged arrays
Jagged arrays are declared using successive square brackets to represent each dimension.
Here is an example of declaring a jagged two-dimensional array, where the outermost
dimension is 3:

The inner dimensions aren’t specified in the declaration because, unlike a rectangular array,
each inner array can be an arbitrary length. Each inner array is implicitly initialized to null
rather than an empty array.

A jagged array can be initialized as follows (to create an array identical to the previous
example with an additional element at the end):

Example Program,

Prepared By: Raju Poudel [Lecturer - MMC] 16


Simplified Array Initialization Expressions

Strings
In C#, a string is a series of characters that is used to represent text. It can be a character, a
word or a long passage surrounded with the double quotes.
The maximum size of a String object in memory is 2GB or about 1 billion characters. However,
practically it will be less depending upon CPU and memory of the computer.

There two ways to declare a string variable in C#.


• Using System.String class and
• Using string keyword.
Both are the same and make no difference.

string str1 = "Hello"; // uses string keyword


String str2 = "Hello"; // uses System.String class

In C#, a string is a collection or an array of characters. So, string can be created using a char
array or accessed like a char array.

char[] chars = {'H','e','l','l','o'};


string str1 = new string(chars);
String str2 = new String(chars);

In c#, the string is immutable, which means the string object cannot be modified once it is
created. If any changes are made to the string object, like adding or modifying an existing
value, it will simply discard the old instance in memory and create a new instance to hold the
new value.

C# String Properties
Property Description
Chars It helps us to get the characters from the current string object based on the
specified position.
Length It returns the number of characters in the current String object.

Prepared By: Raju Poudel [Lecturer - MMC] 17


C# String Methods
In c#, the string class contains various methods to manipulate string objects based on our
requirements.

The following table lists important string methods available in the c# programming language.

Method Description
Compare(String, It compares two specified String objects and returns an integer that
String) indicates their relative position in the sort order.
Concat(String, It concatenates two specified instances of String.
String)
Contains(String) It returns a value indicating whether a specified substring occurs within
this string. Returns true or false.
Copy(String) It creates a new instance of String with the same value as a specified
String.
Trim() It removes all leading and trailing white-space characters from the
current String object.
ToLower() It converts a given string to a lowercase.
ToUpper() It converts a given string to uppercase.
Split(Char[]) It splits a string into substrings that are based on the characters in
an array.
Substring(int) It retrieves a substring from this instance. The substring starts at a
specified character position and continues to the end of the string.

Example of Compare:

Condition Value
strA == strB 0

strA > strB 1


strA < strB -1

using System;
public class Program
{
public static void Main()
{
string str1="Ram";
string str2="Shyam";
Console.WriteLine(string.Compare(str1,str2));
}
}

Output:
-1

Prepared By: Raju Poudel [Lecturer - MMC] 18


Example of Concat
using System;
public class Program
{
public static void Main()
{
string str1="Raju";
string str2=" Poudel";
Console.WriteLine(string.Concat(str1,str2));
}
}

Output:
Raju Poudel

Example of Substring
using System;
public class Program
{
public static void Main()
{
string str1="I love my country";
//Substring(startindex,length);
string str2=str1.Substring(2,7);
Console.WriteLine(str2);
}
}

Output:
love my

Indexers in C#
In c#, Indexer is a special type of property, and that allows instances of a class or structure
to be indexed same like an array. In c#, the indexer is same as the property, but the only
difference is, the indexer will define this keyword along with the square bracket and
parameters.

The Indexers in C# are the members of a class and if we define indexers in a class then the
class behaves like a virtual array. So, it’s a member of a class that gives access to the values
of a class just like an array.

C# indexers are usually known as smart arrays. A C# indexer is a class property that allows
you to access a member variable of a class or struct using the features of an array. In C#,
indexers are created using this keyword. Indexers in C# are applicable on both classes and
structs.

Prepared By: Raju Poudel [Lecturer - MMC] 19


Syntax of using indexer:
<modifier> <return type> this [argument list]
{
get
{
// your get block code
}
set
{
// your set block code
}
}

Example of Indexer
Let’s examine following example to understand indexer.
First let’s run below code that doesn’t use indexer.

using System;
class Student{
public int sid{get;set;}
public string name{get;set;}
public string address{get;set;}
}

public class Program


{
public static void Main()
{
Student st=new Student();
st[0]=101; //error
Console.WriteLine(st[0]);
//error, we can't access property directly like array
}
}

After running above code we’ll get following error:


Compilation error (line 14, col 3): Cannot apply indexing with [] to an expression
of type 'Student'
Compilation error (line 15, col 21): Cannot apply indexing with [] to an expression
of type 'Student'

This is because we cannot apply indexing directly to a class. We can do indexing on an array
but we cannot do the same thing with a user-defined class like Student.
An array is a predefined class and all the logic’s are implemented in that class for indexing so
that we can access them using indexes. But Student is a user-defined class and we have not
implemented any logic to access the class like an array.

If you want to access the class like an array then first you need to define an indexer in the
class. Once you define an indexer in the class then you can start accessing the values of the
class by using the index position.

Prepared By: Raju Poudel [Lecturer - MMC] 20


Example is shown below,

using System;
class Student{
public int sid{get;set;}
public string name{get;set;}
public string address{get;set;}

public string this[int index]{


//returns value
get{
if(index==0)
return sid.ToString();
else if(index==1)
return name;
else if(index==2)
return address;
else
return null;
}
//assigns value
set{
if(index==0)
sid=Convert.ToInt32(value);
else if(index==1)
name=value;
else if(index==2)
address=value;
}
}
}

public class Program


{
public static void Main()
{
Student st=new Student();
//setting value
st[0]="101";
st[1]="Ram";
st[2]="Birtamod";
//accessing values
Console.WriteLine(st[0]+"\t"+st[1]+"\t"+st[2]);
}
}

Output:
101 Ram Birtamod

Prepared By: Raju Poudel [Lecturer - MMC] 21


Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism
in java by which one class is allow to inherit the features (fields and methods) of another
class.
The process by which one class acquires the properties (data members) and
functionalities(methods) of another class is called inheritance. The aim of inheritance is to
provide the reusability of code so that a class has to write only the unique features and rest
of the common properties and functionalities can be extended from the another class.
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship. Inheritance is used in java for the following:
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance


class Subclass-name : Superclass-name
{
//methods and fields
}

The : indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
In the terminology of C#, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.

Types of inheritance in C#
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In C# programming, multiple and hybrid inheritance is supported through interface only.

Prepared By: Raju Poudel [Lecturer - MMC] 22


1. Single Inheritance
Single Inheritance refers to a child and parent class relationship where a class extends the
another class.

using System;
class A
{
public int a=10, b=5;
}

class B : A
{
int a=30, b=5;
public void test()
{
Console.WriteLine("Value of a is: "+a);
Console.WriteLine("Value of a is: " + base.a);
}
}

//driver class
class Inherit
{
static void Main(string[] args)
{
B obj = new B();

Prepared By: Raju Poudel [Lecturer - MMC] 23


obj.test();
Console.ReadLine();
}
}

2. Multilevel Inheritance
Multilevel inheritance refers to a child and parent class relationship where a class extends the
child class. For example, class C extends class B and class B extends class A.

class A
{
public int a, b, c;

public void ReadData(int a, int b)


{
this.a = a;
this.b = b;
}

public void Display()


{
Console.WriteLine("Value of a is: "+a);
Console.WriteLine("Value of b is: " + b);
}
}

class B : A
{
public void Add()
{
base.c = base.a + base.b;
Console.WriteLine("Sum="+base.c);
}
}

class C : B
{
public void Sub()
{
base.c = base.a - base.b;
Console.WriteLine("Difference=" + base.c);
}
}

class Level
{
static void Main()
{
A7 obj = new A7();
obj.ReadData(20,5);
obj.Display();

Prepared By: Raju Poudel [Lecturer - MMC] 24


obj.Add();
obj.Sub();

Console.ReadLine();
}
}

3. Hierarchical Inheritance
Hierarchical inheritance refers to a child and parent class relationship where more than one
classes extends the same class. For example, classes B, C & D extends the same class A.

class Polygon
{
public int dim1,dim2;
public void ReadDimension(int dim1, int dim2)
{
this.dim1 = dim1;
this.dim2 = dim2;
}
}

class Rectangle : Polygon


{
public void AreaRec()
{
base.ReadDimension(10,5);
int area = base.dim1 * base.dim2;
Console.WriteLine("Area of Rectangle="+area);
}
}

class Traingle : Polygon


{
public void AreaTri()
{
base.ReadDimension(10,5);
double area = 0.5*base.dim1 * base.dim2;
Console.WriteLine("Area of Triangle=" + area);
}
}

//driver class
class Hier
{
static void Main()
{
Traingle tri = new Traingle();
//tri.ReadDimension(10,5);
tri.AreaTri();

Rectangle rec = new Rectangle();


//rec.ReadDimension(10,7);

Prepared By: Raju Poudel [Lecturer - MMC] 25


rec.AreaRec();

Console.ReadLine();
}
}

4. Multiple Inheritance
When one class extends more than one classes then this is called multiple inheritance. For
example: Class C extends class A and B then this type of inheritance is known as multiple
inheritance.
C# doesn’t allow multiple inheritance. We can use interfaces instead of classes to achieve the
same purpose.

interface IA
{
// doesn't contain fields
int CalculateArea();
int CalculatePerimeter();
}

class CA
{
public int l, b;
public void ReadData(int l,int b)
{
this.l = l;
this.b = b;
}
}

class BB : CA, IA
{
public int CalculateArea()
{
ReadData(10,5);
int area=l*b;
return area;
}

public int CalculatePerimeter()


{
ReadData(15, 10);
int peri = 2*(l+b);
return peri;
}
}

//driver class
class Inter
{
static void Main(string[] args)
{

Prepared By: Raju Poudel [Lecturer - MMC] 26


BB obj = new BB();
//int area=obj.CalculateArea();
//int peri=obj.CalculatePerimeter();

Console.WriteLine("Area of Rectangle=" +
obj.CalculateArea());
Console.WriteLine("Perimeter of Rectangle=" +
obj.CalculatePerimeter());

Console.ReadKey();
}
}

The base Keyword


We can use the base keyword to access the fields of the base class within derived class. It is
useful if base and derived classes have the same fields.
If derived class doesn't define same field, there is no need to use base keyword. Base class
field can be directly accessed by the derived class.

using System;

class A{
public int a=10;
}

class B:A{
public int a=20;
public void Display(){
Console.WriteLine("A in base class={0}",base.a);
Console.WriteLine("A in derived class={0}",a);
}
}

public class Program


{
public static void Main()
{
B obj=new B();
obj.Display();
}
}

Output:
A in base class=10
A in derived class=20

Prepared By: Raju Poudel [Lecturer - MMC] 27


Polymorphism
Polymorphism in C# is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

Method Overloading
Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different. It is similar to constructor overloading in
Java, that allows a class to have more than one constructor having different argument lists.
In order to overload a method, the argument lists of the methods must differ in either of
these:

a) Number of parameters.
add(int, int)
add(int, int, int)
b) Data type of parameters.
add(int, int)
add(int, float)
c) Sequence of Data type of parameters.
add(int, float)
add(float, int)

Example of Method Overloading

using System;
class A{
public void Add(int a,int b){
int sum=a+b;
Console.WriteLine("Sum={0}",sum);
}

public void Add(double a,double b){


double sum=a+b;
Console.WriteLine("Sum={0}",sum);
}

Prepared By: Raju Poudel [Lecturer - MMC] 28


public void Add(int a,int b, int c){
int sum=a+b+c;
Console.WriteLine("Sum={0}",sum);
}
}

public class Program


{
public static void Main()
{
A obj=new A();
obj.Add(10,20);
obj.Add(10,20,30);
obj.Add(10.4,11.3);
}
}

Output:
Sum=30
Sum=60
Sum=21.7

Method Overriding
Method overriding in C# allows programmers to create base classes that allows its inherited
classes to override same name methods when implementing in their class for different
purpose. This method is also used to enforce some must implement features in derived
classes.

Important points:
• Method overriding is only possible in derived classes, not within the same class where
the method is declared.
• Base class must use the virtual or abstract keywords to declare a method. Then only
can a method be overridden

Here is an example of method overriding.

public class Account


{
public virtual int balance()
{
return 10;
}
}

public class Amount : Account


{

public override int balance()


{
return 500;
}

Prepared By: Raju Poudel [Lecturer - MMC] 29


}

class Test
{
static void Main()
{
Amount obj = new Amount();
int balance = obj.balance();
Console.WriteLine("Balance is: "+balance);
Console.ReadKey();
}
}

Output:
Balance is 500

Virtual Method
A virtual method is a method that can be redefined in derived classes. A virtual method has
an implementation in a base class as well as derived the class. It is used when a method's
basic functionality is the same but sometimes more functionality is needed in the derived
class. A virtual method is created in the base class that can be overriden in the derived class.
We create a virtual method in the base class using the virtual keyword and that method is
overriden in the derived class using the override keyword.

Features of virtual method


• By default, methods are non-virtual. We can't override a non-virtual method.
• We can't use the virtual modifier with the static, abstract, private or override
modifiers.
• If class is not inherited, behaviour of virtual method is same as non-virtual method,
but in case of inheritance it is used for method overriding.

Behaviour of virtual method without inheritance – same as non virtual

class Vir
{
public virtual void message()
{
Console.WriteLine("This is test");
}
}

class Program
{
static void Main(string[] args)
{
Vir obj = new Vir();
obj.message();
Console.ReadKey();
}
}

Prepared By: Raju Poudel [Lecturer - MMC] 30


Behaviour of virtual method with inheritance – used for overriding

class Vir
{
public virtual void message()
{
Console.WriteLine("This is test");
}
}

class Vir1 : Vir


{
public override void message()
{
Console.WriteLine("This is test1");
}
}

class Program
{
static void Main(string[] args)
{
Vir1 obj = new Vir1();
obj.message();
Console.ReadKey();
}
}

Output:
This is test1

Abstract Class
A class declared as abstract can never be instantiated. We can’t create object of abstract
class.
If a class is defined as abstract then we can't create an instance of that class. By the creation
of the derived class object where an abstract class is inherited from, we can call the method
of the abstract class.
Abstract class can be created using abstract keyword.

using System;
abstract class A{
public void Message1(){
Console.WriteLine("Inside class A");
}
}

class B : A{
public void Message2(){
Console.WriteLine("Inside class B");
}
}

Prepared By: Raju Poudel [Lecturer - MMC] 31


public class Program
{
public static void Main()
{
B obj=new B();
obj.Message1();
obj.Message2();
}
}

Output:
Inside class A
Inside class B

Abstract Members
An Abstract method is a method without a body. The implementation of an abstract method
is done by a derived class. When the derived class inherits the abstract method from the
abstract class, it must override the abstract method. This requirement is enforced at compile
time and is also called dynamic polymorphism.

Abstract members are used to achieve total abstraction.

using System;
abstract class A{
//abstract method
public abstract void Add(int a,int b);
public abstract void Display();
}

class B:A{
int sum;
public override void Add(int a,int b){
sum=a+b;
}
public override void Display(){
Console.WriteLine("Sum={0}",sum);
}
}

public class Program


{
public static void Main()
{
B obj=new B();
obj.Add(10,20);
obj.Display();
}
}

Output:
Sum=30

Prepared By: Raju Poudel [Lecturer - MMC] 32


Interface in C#
An interface looks like a class, but has no implementation. The only thing it contains are
declarations of events, indexers, methods and/or properties. The reason interfaces only
provide declarations is because they are inherited by structs and classes, that must provide
an implementation for each interface member declared.

Like a class, an interface can have methods and properties, but the methods declared in
interface are by default abstract (only method signature, no body).
v Interfaces specify what a class must do and not how. It is the blueprint of the class.
v An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move (). So it specifies a
set of methods that the class has to implement.
v If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then class must be declared abstract.

Why do we use interface?


• It is used to achieve total abstraction.
• Since C# does not support multiple inheritance in case of class, but by using interface
it can achieve multiple inheritance.

interface IA
{
// doesn't contain fields
void GetData(int l,int b);
int CalculateArea();
int CalculatePerimeter();
}

class BB : IA
{
int l, b;
public void GetData(int l, int b)
{
this.l = l;
this.b = b;
}
public int CalculateArea()
{
int area=l*b;
return area;
}

public int CalculatePerimeter()


{
int peri = 2*(l+b);
return peri;
}
}

Prepared By: Raju Poudel [Lecturer - MMC] 33


//driver class
class Inter
{
static void Main(string[] args)
{
BB obj = new BB();
obj.GetData(10,5);
Console.WriteLine("Area of Rectangle=" + obj.CalculateArea());
Console.WriteLine("Perimeter of Rectangle=" +
obj.CalculatePerimeter());

Console.ReadKey();
}
}

Output:
Area of Rectangle=50
Perimeter of Rectangle=30

Sealed Class
Sealed classes are used to restrict the inheritance feature of object oriented programming.
Once a class is defined as a sealed class, this class cannot be inherited. In C#, the sealed
modifier is used to declare a class as sealed. If a class is derived from a sealed class, compiler
throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
// Sealed class
sealed class SealedClass{
}

using System;
sealed class A{
int sum;
public void Add(int a,int b){
sum=a+b;
Console.WriteLine("Sum={0}",sum);
}
}

public class Program


{
public static void Main()
{
A obj=new A();
obj.Add(10,20);
}
}

Output:
Sum=30

Prepared By: Raju Poudel [Lecturer - MMC] 34


Partial Class
In c#, a partial class is useful to split the functionality of a particular class into multiple class
files, and all these files will be combined into one single class file when the application is
compiled.
While working on large-scale projects, multiple developers want to work on the same class
file simultaneously. To solve this problem, C# provides an ability to spread the functionality
of a particular class into multiple class files using partial keyword.

In C#, we can use partial keyword to split the definition of a particular class, structure,
interface, or method over two or more source files.

using System;

partial class A{
int sum;
public void Add(int a, int b){
sum=a+b;
}
}

partial class A{
public void Display(){
Console.WriteLine("Sum={0}",sum);
}
}

public class Program


{
public static void Main()
{
A obj=new A();
obj.Add(10,20);
obj.Display();
}
}

Output:
Sum=30

Structs
A struct is similar to a class, with the following key differences:
• A struct is a value type, whereas a class is a reference type.
• A struct does not support inheritance
.
A struct can have all the members a class can, except the following:
• A parameter less constructor
• Field initializers
• A finalizer
• Virtual or protected members

Prepared By: Raju Poudel [Lecturer - MMC] 35


Here is an example of declaring and calling struct:

Enums in C#
An enum is a special "class" that represents a group of constants (unchangeable/read-only
variables).

To create an enum, use the enum keyword (instead of class or interface), and separate the
enum items with a comma:

enum Level
{
Low,
Medium,
High
}

class Program
{
static void Main(string[] args)
{
Level myVar = Level.Medium;
Console.WriteLine(myVar);
}
}

Output:
Medium

Prepared By: Raju Poudel [Lecturer - MMC] 36


You can also have an enum inside a class:

class Program
{
enum Level
{
Low,
Medium,
High
}
static void Main(string[] args)
{
Level myVar = Level.Medium;
Console.WriteLine(myVar);
}
}

Output:
Medium

Delegates
A delegate is an object that knows how to call a method.
A delegate type defines the kind of method that delegate instances can call. Specifically, it
defines the method’s return type and its parameter types.
Delegates are especially used for implementing events and the call-back methods. All
delegates are implicitly derived from the System.Delegate class. It provides a way which tells
which method is to be called when an event is triggered.
For example, if you click an Button on a form (Windows Form application), the program
would call a specific method.
In simple words, it is a type that represents references to methods with a particular parameter
list and return type and then calls the method in a program for execution when it is needed.

Declaring Delegates
Delegate type can be declared using the delegate keyword. Once a delegate is declared,
delegate instance will refer and call those methods whose return type and parameter-list
matches with the delegate declaration.
Syntax:
[modifier] delegate [return_type] [delegate_name] ([parameter_list]);
modifier: It is the required modifier which defines the access of delegate and it is optional to
use.
delegate: It is the keyword which is used to define the delegate.
return_type: It is the type of value returned by the methods which the delegate will be going
to call. It can be void. A method must have the same return type as the delegate.
delegate_name: It is the user-defined name or identifier for the delegate.
parameter_list: This contains the parameters which are required by the method when called
through the delegate.

Prepared By: Raju Poudel [Lecturer - MMC] 37


public delegate int DelegateTest(int x, int y, int z);

Note: A delegate will call only a method which agrees with its signature and return type. A
method can be a static method associated with a class or can be an instance method
associated with an object, it doesn’t matter.

Instantiation & Invocation of Delegates


Once a delegate type is declared, a delegate object must be created with the new keyword
and be associated with a particular method. When creating a delegate, the argument passed
to the new expression is written similar to a method call, but without the arguments to the
method. For example

[delegate_name] [instance_name] = new [delegate_name](calling_method_name);

DelegateTest obj = new DelegateTest (MyMethod);


// here,
// " DelegateTest" is delegate name.
// " obj" is instance_name
// " MyMethod" is the calling method.
The following defines a delegate type called Transformer:
delegate int Transformer (int x);

Transformer is compatible with any method with an int return type and a single int
parameter, such as this:
static int Square (int x) { return x * x; }
or
static int Square (int x) => x * x;

Assigning a method to a delegate variable creates a delegate instance:


Transformer t = new Transformer (Square);
Or
Transformer t = Square;

which can be invoked in the same way as a method:


int answer = t(3); // answer is 9

Example of simple delegate is shown below:


public delegate int MyDelegate(int x);
class DelegateTest
{
static int MyMethod(int x)
{
return x * x;
}

static void Main(string[] agrs)

Prepared By: Raju Poudel [Lecturer - MMC] 38


{
MyDelegate del = new MyDelegate(MyMethod);
int res = del(5); //25
Console.WriteLine("Result is : "+res);
Console.ReadKey();
}
}

Output:
Result is : 25

Example 2

using System;

delegate int NumberChanger(int n);

class TestDelegate {
static int num = 10;

public static int AddNum(int p) {


num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);

//calling the methods using the delegate objects


nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}

Output:
Value of Num: 35
Value of Num: 175

Prepared By: Raju Poudel [Lecturer - MMC] 39


Example 3

class Test
{
public delegate void addnum(int a, int b);
public delegate void subnum(int a, int b);

// method "sum"
public void sum(int a, int b)
{
Console.WriteLine("(100 + 40) = {0}", a + b);
}

// method "subtract"
public void subtract(int a, int b)
{
Console.WriteLine("(100 - 60) = {0}", a - b);
}

// Main Method
public static void Main(String[] args)
{
addnum del_obj1 = new addnum(obj.sum);
subnum del_obj2 = new subnum(obj.subtract);

// pass the values to the methods by delegate object


del_obj1(100, 40);
del_obj2(100, 60);

// These can be written as using


// "Invoke" method
// del_obj1.Invoke(100, 40);
// del_obj2.Invoke(100, 60);
}
}

Output:
(100 + 40) = 140
(100 - 60) = 40

Multicast Delegates
All delegate instances have multicast capability. This means that a delegate instance can
reference not just a single target method, but also a list of target methods.
The + and += operators combine delegate instances. For example:
SomeDelegate d = SomeMethod1;
d += SomeMethod2;

The last line is functionally the same as:


d = d + SomeMethod2;
Invoking d will now call both SomeMethod1 and SomeMethod2. Delegates are invoked in
the order they are added.

Prepared By: Raju Poudel [Lecturer - MMC] 40


The - and -= operators remove the right delegate operand from the left delegate operand.
For example:
d -= SomeMethod1;
Invoking d will now cause only SomeMethod2 to be invoked.

Calling + or += on a delegate variable with a null value works, and it is equivalent to


assigning the variable to a new value:
SomeDelegate d = null;
d += SomeMethod1; // Equivalent (when d is null) to d = SomeMethod1;
Similarly, calling -= on a delegate variable with a single target is equivalent to assigning null
to that variable.

Example of multicasting delegates

using System;

delegate int NumberChanger(int n);


class TestDelegate {
static int num = 10;

public static int AddNum(int p) {


num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);

nc = nc1;
nc += nc2;

//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}

Output
Value of Num: 75

Prepared By: Raju Poudel [Lecturer - MMC] 41


Asynchronous Programming
Asynchronous programming in C# is an efficient approach towards activities blocked or
access is delayed. If an activity is blocked like this in a synchronous process, then the complete
application waits and it takes more time. The application stops responding. Using the
asynchronous approach, the applications continue with other tasks as well.

The async and await keywords in C# are used in async programming. Using them, you can
work with .NET Framework resources, .NET Core, etc. Asynchronous methods defined using
the async keyword are called async methods.

Nowadays, Asynchronous programming is very popular with the help of the async and await
keywords in C#. When we are dealing with UI, and on button click, we use a long-running
method like reading a large file or something else which will take a long time, in that case, the
entire application must wait to complete the whole task. In other words, if any process is
blocked in a synchronous application, the whole application gets blocked, and our application
stops responding until the whole task completes.

Asynchronous programming is very helpful in this condition. By using Asynchronous


programming, the Application can continue with the other work that does not depend on the
completion of the entire task.

We will get all the benefits of traditional Asynchronous programming with much less effort
with the help of async and await keywords.
Suppose we are using two methods as Method1 and Method2 respectively, and both the
methods are not dependent on each other, and Method1 takes a long time to complete its
task. In Synchronous programming, it will execute the first Method1 and it will wait for the
completion of this method, and then it will execute Method2. Thus, it will be a time-intensive
process even though both methods are not depending on each other.

Example of Aysnc/Await Pattern in C#

using System;
using System.Threading.Tasks;
class A{
int sum;
public async Task Add(int a,int b){
sum=a+b;
}

public async void Display(){


await Add(30,20);
Console.WriteLine("Sum={0}",sum);
}
}

public class Program


{
public static void Main()
{

Prepared By: Raju Poudel [Lecturer - MMC] 42


A obj=new A();
obj.Display();
}
}

Output:
Sum=50

Collections in C#
C# collection types are designed to store, manage and manipulate similar data more
efficiently. Data manipulation includes adding, removing, finding, and inserting data in the
collection.
Collection types implement the following common functionality:
• Adding and inserting items to a collection
• Removing items from a collection
• Finding, sorting, searching items
• Replacing items
• Copy and clone collections and items
• Capacity and Count properties to find the capacity of the collection and number of
items in the collection

.NET supports two types of collections, generic collections and non-generic collections. Prior
to .NET 2.0, it was just collections and when generics were added to .NET, generics collections
were added as well.

C# Non-Generic Collections
In c#, non-generic collection classes are useful to store elements of different data types, and
these are provided by System.Collections namespace.

Class Description
ArrayList It is useful to represent an array of objects whose size is dynamically increased as
required.
Queue It is useful to represent a FIFO (First In, First Out) collection of objects.
Stack It is useful to represent a LIFO (Last in, First Out) collection of objects.
Hashtable It is useful to represent a collection of key/value pairs organized based on the key's hash
code.

C# Generic Collections
In c#, generic collections will enforce a type safety so we can store only the elements with the
same data type, and these are provided by System.Collections.Generic namespace.

Class Description
List It is useful to represent a list of objects that can be accessed by an index.
Queue It is useful to represent a FIFO (First In, First Out) collection of objects.
Stack It is useful to represent a LIFO (Last in, First Out) collection of objects.
SortedList<K,V> It is useful to represent a collection of key/value pairs sorted by a key.
Dictionary<K,V> It is useful to represent a collection of key/value pairs organized based on the key.

Prepared By: Raju Poudel [Lecturer - MMC] 43


Dictionary
Dictionaries are also known as maps or hash tables. It represents a data structure that allows
you to access an element based on a key. One of the significant features of a dictionary is
faster lookup; you can add or remove items without the performance overhead.
.Net offers several dictionary classes, for instance Dictionary<TKey, TValue>. The type
parameters TKey and TValue represent the types of the keys and the values it can store,
respectively.

using System.Collections.Generic;
public class Program
{
static void Main(string[] args)
{
//define Dictionary collection
Dictionary<int, string> dObj = new Dictionary<int,
string>(5);
//add elements to Dictionary
dObj.Add(1, 1, "Tom");
dObj.Add(2, "John");
dObj.Add(3, "Maria");
dObj.Add(4, "Max");
dObj.Add(5, "Ram");

//print data
for (int i = 1; i <= dObj.Count; i++)
{
Console.WriteLine(dObj[i]);
}
Console.ReadKey();
}
}

Queues
Queues are a special type of container that ensures the items are being accessed in a FIFO
(first in, first out) manner. Queue collections are most appropriate for implementing
messaging components. We can define a Queue collection object using the following syntax:
Queue qObj = new Queue();
The Queue collection property, methods and other specification definitions are found under
the Sysyem.Collection namespace. The following table defines the key members;

System.Collection.Queue Members Definition


Enqueue() Add an object to the end of the queue.
Dequeue() Removes an object from the beginning of the
queue.
Peek() Return the object at the beginning of the queue
without removing it.

Prepared By: Raju Poudel [Lecturer - MMC] 44


using System.Collections.Generic;
class Program {
static void Main(string[] args) {
Queue < string > queue1 = new Queue < string > ();
queue1.Enqueue("MCA");
queue1.Enqueue("MBA");
queue1.Enqueue("BCA");
queue1.Enqueue("BBA");

Console.WriteLine("The elements in the queue are:");


foreach(string s in queue1) {
Console.WriteLine(s);
}

queue1.Dequeue(); //Removes the first element that


enter in the queue here the first element is MCA
queue1.Dequeue(); //Removes MBA

Console.WriteLine("After removal the elements in the


queue are:");
foreach(string s in queue1) {
Console.WriteLine(s);
}
}
}

Stacks
A Stack collection is an abstraction of LIFO (last in, first out). We can define a Stack collection
object using the following syntax:
Stack qObj = new Stack();
The following table illustrates the key members of a stack;

System.Collection.Stack Members Definition


Contains() Returns true if a specific element is found in the
collection.
Clear() Removes all the elements of the collection.
Peek() Previews the most recent element on the stack.
Push() It pushes elements onto the stack.
Pop() Return and remove the top elements of the
stack.

class Program {
static void Main(string[] args) {
Stack < string > stack1 = newStack < string > ();
stack1.Push("************");
stack1.Push("MCA");
stack1.Push("MBA");
stack1.Push("BCA");
stack1.Push("BBA");

Prepared By: Raju Poudel [Lecturer - MMC] 45


stack1.Push("***********");
stack1.Push("**Courses**");
stack1.Push("***********");
Console.WriteLine("The elements in the stack1 are
as:");
foreach(string s in stack1) {
Console.WriteLine(s);
}

//For remove/or pop the element pop() method is used


stack1.Pop();
stack1.Pop();
stack1.Pop();
Console.WriteLine("After removal/or pop the element
the stack is as:");
//the element that inserted in last is remove firstly.

foreach(string s in stack1) {
Console.WriteLine(s);
}
}
}

List
List<T> class in C# represents a strongly typed list of objects. List<T> provides functionality to
create a list of objects, find list items, sort list, search list, and manipulate list items. In List<T>,
T is the type of objects.

Adding Elements
// Dynamic ArrayList with no size limit
List<int> numberList = new List<int>();
numberList.Add(32);
numberList.Add(21);
numberList.Add(45);
numberList.Add(11);
numberList.Add(89);
// List of string
List<string> authors = new List<string>(5);
authors.Add("Mahesh Chand");
authors.Add("Chris Love");
authors.Add("Allen O'neill");
authors.Add("Naveen Sharma");
authors.Add("Monica Rathbun");
authors.Add("David McCarter");

// Collection of string
string[] animals = { "Cow", "Camel", "Elephant" };
// Create a List and add a collection
List<string> animalsList = new List<string>();
animalsList.AddRange(animals);
foreach (string a in animalsList)
Console.WriteLine(a);

Prepared By: Raju Poudel [Lecturer - MMC] 46


Remove Elements
// Remove an item
authors.Remove("New Author1");

// Remove 3rd item


authors.RemoveAt(3);

// Remove all items


authors.Clear();

Sorting
authors.Sort();

Other Methods
authors.Insert(1,"Shaijal"); //insert item at index 1
authors.Count; //returns total items

Array List
C# ArrayList is a non-generic collection. The ArrayList class represents an array list and it can
contain elements of any data types. The ArrayList class is defined in the System.Collections
namespace. An ArrayList is dynamic array and grows automatically when new items are added
to the collection.

ArrayList personList = new ArrayList();

Insertion
personList.Add("Sandeep");

Removal
// Remove an item
personList.Remove("New Author1");

// Remove 3rd item


personList.RemoveAt(3);

// Remove all items


personList.Clear();

Sorting
personList.Sort();

Other Methods
personList.Insert(1,"Shaijal"); //insert item at index 1
personList.Count; //returns total items

Generic Class
The Generic class can be defined by putting the <T> sign after the class name. It isn't
mandatory to put the "T" word in the Generic type definition. You can use any word in the
TestClass<> class declaration.
public class TestClass<T> { }

Prepared By: Raju Poudel [Lecturer - MMC] 47


Example of Generic Class

using System.Collections.Generic;
class Test<T>
{
T[] t=new T[5];
int count = 0;
public void addItem(T item)
{
if (count < 5)
{
t[count] = item;
count++;
}
else
{
Console.WriteLine("Overflow exists");
}
}

public void displayItem()


{
for (int i = 0; i < count; i++)
{
Console.WriteLine("Item at index {0} is {1}",i,t[i]);
}
}
}

class GenericEx
{
static void Main()
{
Test<int> obj = new Test<int>();
obj.addItem(10);
obj.addItem(20);
obj.addItem(30);
obj.addItem(40);
obj.addItem(50);
//obj.addItem(60); //overflow exists
obj.displayItem();
Console.ReadKey();
}
}

Output
Item at index 0 is 10
Item at index 1 is 20
Item at index 2 is 30
Item at index 3 is 40
Item at index 4 is 50

Prepared By: Raju Poudel [Lecturer - MMC] 48


Introduction to LINQ
LINQ (Language Integrated Query) is uniform query syntax in C# to retrieve data from
different sources and formats. It is integrated in C#, thereby eliminating the mismatch
between programming languages and databases, as well as providing a single querying
interface for different types of data sources.

For example, SQL is a Structured Query Language used to save and retrieve data from a
database. In the same way, LINQ is a structured query syntax built in C# to retrieve data from
different types of data sources such as collections, ADO.Net DataSet, XML Docs, web service
and MS SQL Server and other databases.

LINQ queries return results as objects. It enables you to uses object-oriented approach on the
result set and not to worry about transforming different formats of results into objects.

The following example demonstrates a simple LINQ query that gets all strings from an
array which contains 'a'.

Example: LINQ Query to Array


// Data source
string[] names = {"Bill", "Steve", "James", "Mohan" };
// LINQ Query
var myLinqQuery = from name in names
where name.Contains('a')
select name;
// Query execution
foreach(string name in myLinqQuery)
Console.Write(name + " ");

Prepared By: Raju Poudel [Lecturer - MMC] 49


Example: LINQ Query to List
// string collection
List<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};

var result = from s in stringList


where s.Contains("Tutorials")
select s;

foreach(string value in result)


Console.Write(value + " ");

LINQ Operators
Classification LINQ Operators
Filtering Where, OfType
Sorting OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
Grouping GroupBy, ToLookup
Join GroupJoin, Join
Projection Select, SelectMany
Aggregation Aggregate, Average, Count, LongCount, Max, Min, Sum
Quantifiers All, Any, Contains
Elements ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last,
LastOrDefault, Single, SingleOrDefault
Set Distinct, Except, Intersect, Union
Partitioning Skip, SkipWhile, Take, TakeWhile
Concatenation Concat
Equality Equals,SequenceEqual
Generation DefaultEmpty, Empty, Range, Repeat
Conversion AsEnumerable, AsQueryable, Cast, ToArray, ToDictionary, ToList

Prepared By: Raju Poudel [Lecturer - MMC] 50


Lambda Expressions
Lambda expressions in C# are used like anonymous functions, with the difference that in
Lambda expressions you don’t need to specify the type of the value that you input thus
making it more flexible to use.
The ‘=>’ is the lambda operator which is used in all lambda expressions. The Lambda
expression is divided into two parts, the left side is the input and the right is the expression.

The Lambda Expressions can be of two types:


1. Expression Lambda: Consists of the input and the expression.
Syntax:
input => expression;
2. Statement Lambda: Consists of the input and a set of statements to be executed. It
can be used along with delegates.
Syntax:
input => { statements };

Basic example of lambda expression:

class LambdaTest
{
static int test1() => 5;
static int test2(int x) => x + 10;

static void Main(string[] args)


{
int x=test1();
int res = test2(x);
Console.WriteLine("Result is: "+res);
}
}

Output:
Result is: 15

Unlike an expression lambda, a statement lambda can contain multiple statements separated
by semicolons. It is used with delegates.

delegate void ModifyInt(int input);

ModifyInt addOneAndTellMe = x =>


{
int result = x + 1;
Console.WriteLine(result);
};

Prepared By: Raju Poudel [Lecturer - MMC] 51


Example: Use of Lambda Expression in LINQ
// string collection
List<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};

// LINQ Query Syntax


var result = stringList.Where(s => s.Contains("Tutorials"));

Exception Handling
A try statement specifies a code block subject to error-handling or clean-up code. The try
block must be followed by a catch block, a finally block, or both. The catch block executes
when an error occurs in the try block. The finally block executes after execution leaves the try
block (or if present, the catch block), to per- form clean-up code, whether or not an error
occurred.
A catch block has access to an Exception object that contains information about the error.
You use a catch block to either compensate for the error or re throw the exception. You re
throw an exception if you merely want to log the problem, or if you want to re throw a new,
higher-level exception type.
A finally block adds determinism to your program: the CLR endeavours to always execute it.
It’s useful for clean-up tasks such as closing network connections.

Consider the following program:

Prepared By: Raju Poudel [Lecturer - MMC] 52


Because x is zero, the runtime throws a DivideByZeroException, and our program terminates.
We can prevent this by catching the exception as follows:

Prepared By: Raju Poudel [Lecturer - MMC] 53


The catch Clause
A catch clause specifies what type of exception to catch. This must either be System.Exception
or a subclass of System.Exception.
You can handle multiple exception types with multiple catch clauses:

The finally Block


A finally block always executes—whether or not an exception is thrown and whether or not
the try block runs to completion. finally blocks are typically used for clean-up code.
A finally block executes either:
• After a catch block finishes
• After control leaves the try block because of a jump statement (e.g., return or goto)
• After the try block ends

The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class –

Sr.No. Exception Class & Description


1 System.IO.IOException
Handles I/O errors.
2 System.IndexOutOfRangeException
Handles errors generated when a method refers to an array index out of range.
3 System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.
4 System.NullReferenceException
Handles errors generated from referencing a null object.
5 System.DivideByZeroException
Handles errors generated from dividing a dividend with zero.

Prepared By: Raju Poudel [Lecturer - MMC] 54


6 System.InvalidCastException
Handles errors generated during typecasting.
7 System.OutOfMemoryException
Handles errors generated from insufficient free memory.
8 System.StackOverflowException
Handles errors generated from stack overflow.

Attributes in C#
Attributes are used in C# to convey declarative information or metadata about various code
elements such as methods, assemblies, properties, types, etc.
Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ])
on top of the required code element.

Syntax for specifying an attribute is as follows −


[attribute(positional_parameters, name_parameter = value, ...)]
element

There are two types of Attributes implementations provided by the .NET Framework are:
1. Predefined Attributes
2. Custom Attributes

Properties of Attributes:
• Attributes can have arguments just like methods, properties, etc. can have arguments.
• Attributes can have zero or more parameters.
• Different code elements such as methods, assemblies, properties, types, etc. can have one or
multiple attributes.
• Reflection can be used to obtain the metadata of the program by accessing the attributes at
run-time.
• Attributes are generally derived from the System.Attribute Class.

Predefined Attributes
Predefined attributes are those attributes that are a part of the .NET Framework Class Library
and are supported by the C# compiler for a specific purpose.

Attributes Description
[WebMethod] This is used to create XML web services. Also, the marked method is
invoked by the HTTP request.
[Obsolete] Any member or type can be marked as deprecated using [Obsolete].
The compiler issues a warning if Obsolete is used.
[Serializable] A class persists with its current state by marking this attribute.
[NonSerializable] A class or field should not be persisted using this attribute.
[DllImport] This allows a call by the code to the unmanaged library.

Prepared By: Raju Poudel [Lecturer - MMC] 55


Program to implement Obsolete attribute in C#

using System;
class A{
[Obsolete("Do not write Test as method!",false)]
public void Test(){
Console.WriteLine("Inside class A!");
}
}

public class Program


{
public static void Main(string[] args)
{
A obj=new A();
obj.Test();
}
}

Output:
main.cs(10,13): warning CS0618: ` A.Test()' is obsolete: `Do not write Test
as method!'

Inside class A

Attribute Class
In an attribute class, you will define the members that support the attribute.
Steps for creating Custom Attributes:
• Define a custom attribute class that is derived from System.Attribute class.
• The custom attribute class name should have the suffix Attribute.
• Use the attribute AttributeUsage to specify the usage of the custom attribute class created.
• Create the constructor and the accessible properties of the custom attribute class

using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method |
AttributeTargets.Constructor)]
//[AttributeUsage(AttributeTargets.All)]
class InfoAttribute : Attribute{
string comment{get;set;}
public InfoAttribute(string comment){
this.comment=comment;
}
}

//using above attribute


[Info("Class")]
class A{
string name;
[Info("Constructor")]
public A(string name){
this.name=name;
}

Prepared By: Raju Poudel [Lecturer - MMC] 56


[Info("Method")]
public void Display(){
Console.WriteLine("Name is:{0}",name);
}
}

public class Program


{
public static void Main(string[] args)
{
A obj=new A("Ram");
obj.Display();
}
}

Output:
Name is:Ram

Attribute Targets
These are the most common attribute targets, or pieces of code infrastructure that can be
marked with an attribute.

Target Description
Type Attributes belong to a delegate, class, struct, interface, or enum
Method Attributes relate to a method or property accessors (get / set)
Property Attributes relate to properties
Assembly Attributes relate to the entire assembly
Field Attributes relate to a field on a class or struct
Return Attributes relate to the return value of a method or property accessors
Event Attributes relate to an event
Parameter Attributes relate to parameters of methods or property accessors
Example is already shown above.

Specifying Multiple Attributes


Multiple attributes can be specified for a single code element.Each attribute can be listed either within
the same pair of square brackets separated by a comma or in separate pairs of square brackets or a
combination of the two.
The following three examples are semantically identical:

[Serializable, Obsolete, CLSCompliant(false)]


public class Bar {...}

[Serializable] [Obsolete] [CLSCompliant(false)]


public class Bar {...}

[Serializable, Obsolete]
[CLSCompliant(false)]
public class Bar {...}

Prepared By: Raju Poudel [Lecturer - MMC] 57


Named and Positional Attribute Parameters
Attributes may have parameters.Attribute parameters fall into one of two categories:
positional or named.
• Positional parameters correspond to parameters of the attribute type's public
constructors.
• Named parameters correspond to public fields or public properties on the attribute
type.

When specifying an attribute, you must include positional parameters that correspond to one
of the attribute's constructors.
Named parameters are optional.

In the following example, we apply XmlElementAttribute to a class.

[XmlElement ("Customer", Namespace="http://example.com")]


public class CustomerEntity { ... }

In the above example, the first argument is a positional parameter ; the second is a named
parameter.

Example of Named Attribute Parameters

using System;

[AttributeUsage(AttributeTargets.All)]
class InfoAttribute : Attribute{
public string comment{get;set;}
}

//using above attribute


[Info(comment="Class")]
class A{
public void Msg(){
Console.WriteLine("Inside class A!");
}
}

public class Program


{
public static void Main(string[] args)
{
A obj=new A();
obj.Msg();
}
}

Output:
Inside class A!

Prepared By: Raju Poudel [Lecturer - MMC] 58


File IO
There are two basic operation which is mostly used in file handling is reading and writing of the file.
The file becomes stream when we open the file for writing and reading. A stream is a sequence of
bytes which is used for communication. Two stream can be formed from file one is input stream
which is used to read the file and another is output stream is used to write in the file. In
C#, System.IO namespace contains classes which handle input and output streams and provide
information about file and directory structure.

StreamWriter Class
The StreamWriter class implements TextWriter for writing character to stream in a particular format.
The class contains the following method which are mostly used.

Method Description
Close() Closes the current StreamWriter object and stream associate with it.
Flush() Clears all the data from the buffer and write it in the stream associate with it.
Write() Write data to the stream. It has different overloads for different data types
to write in stream.
WriteLine() It is same as Write() but it adds the newline character at the end of the data.

using System;
using System.IO;
class WriteToFile {
public void Data()
{
// This will create a file named sample.txt
// at the specified location
StreamWriter sw = new StreamWriter("D://test.txt");

// To write on the console screen


Console.WriteLine("Enter the Text that you want to write on File");

// To read the input from the user


string str = Console.ReadLine();

// To write a line in buffer


sw.WriteLine(str);

// To write in output stream


sw.Flush();

// To close the stream


sw.Close();
}
}
// Main Method
static void Main(string[] args)
{
WriteToFile wr = new WriteToFile();
wr.Data();
}
}

Prepared By: Raju Poudel [Lecturer - MMC] 59


StreamReader Class
The StreamReader class implements TextReader for reading character from the stream in a
particular format. The class contains the following method which are mostly used.

Method Description
Close() Closes the current StreamReader object and stream associate with it.
Peek() Returns the next available character but does not consume it.
Read() Reads the next character in input stream and increment characters position by one in
the stream
ReadLine() Reads a line from the input stream and return the data in form of string
Seek() It is use to read/write at the specific location from a file

using System;
using System.IO;
class ReadFile {

public void DataReading()


{
// Taking a new input stream i.e.
// test.txt and opens it
StreamReader sr = new StreamReader("D://test.txt");

// This is use to specify from where


// to start reading input stream
sr.BaseStream.Seek(0, SeekOrigin.Begin);

// To read line from input stream


string str = sr.ReadLine();

// To read the whole file line by line


while (str != null)
{
Console.WriteLine(str);
str = sr.ReadLine();
}
Console.ReadLine();

// to close the stream


sr.Close();
}
}

// Main Method
static void Main(string[] args)
{
ReadFile wr = new ReadFile();
wr.DataReading();
}
}

Prepared By: Raju Poudel [Lecturer - MMC] 60

You might also like