[go: up one dir, main page]

0% found this document useful (0 votes)
42 views152 pages

Unit 1

Uploaded by

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

Unit 1

Uploaded by

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

ASP.

NET Core - I
#2101CS511

Unit-1
C# (C-Sharp)
Fundamentals

Prof. Naimish R. Vadodariya


Computer Science & Engineering
Department
Darshan University, Rajkot
Naimish.vadodariya@darshan.ac.in
8866215253
 Outline
Looping
• Introduction to C#
• Namespace
• Data Types & Variables
• Operators
• Conditions & Looping
• Collection Classes
• Exception Handling
• Classes/Objects
• Constructors
• Access Modifier
• Properties
• Inheritance
• Interface
C#: Introduction
Section - 1
C#: Introduction
 C# is pronounced as "C-Sharp".
 It is an object-oriented programming language created by Microsoft that runs on the .NET
Framework.
 C# has roots from the C family, and the language is close to other popular languages like C+
+ and Java.
 The first version was released in year 2002. The latest version, C# 11, was released in
November 2022.
 It was developed by Microsoft led by Anders Hejlsberg and his team.
 C# is used for:
 Mobile, Desktop, Web Applications
 Web Services
 Web Sites
 Games
 VR, Database Applications
 And much, much more!
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 4
C#: Features
 Object Oriented Language
 C# is an object oriented language.
 This means that development is easier if there are long codes in large projects as compared to procedure
oriented programming languages.
 Structured programming language
 The programs in C# can be structured by breaking them into smaller parts using functions.
 This makes the program easier to understand.
 Simple to use
 It is quite simple to use C# as it has various features and functionalities.
 Moreover, it provides a structured approach that makes the program easier to understand.
 Scalable language
 C# is an automatically scalable as well as updatable language.
 The old files are regularly updated and replaced with new ones.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 5
Namespace
Section - 2
Namespaces
 Namespaces are used in C# to keep one set of names separated from another.
 This is done to organize the classes so, that they are easy to handle.
 If there are two classes with the same names in different namespaces, they do not conflict
with one another.
 It play an important role in managing related classes in C#.
 The .NET Framework uses namespaces to organize its built-in classes.
 We can say it is a container for classes and namespaces.
 There are some built-in namespaces in .NET such as System, System.Linq, System.Web,
etc. Each namespace contains related set of classes.
 In C#, a namespace can be defined using the namespace keyword.
Example: Namespace
1 namespace School
2 {
3 // define classes here
4 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 7
Namespaces Cont..
 The following namespace contains the Student and Course classes.
Example: Namespace
1 namespace School
2 {
3 class Student
4 {
5
6 }
7
8 class Course
9 {
10
11 }
12 }

 Classes under the same namespace can be referred to as namespace.classname syntax.


 For example, the Student class can be accessed as School.Student.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 8
Namespaces Cont..
 The following namespace contains the Student and Course classes.
Example: Namespace Example: Namespace
1 namespace School 1 namespace DUDemo
2 { 2 {
3 class Student 3 class Program
4 { 4 {
5 5 static void Main(string[] args)
6 } 6 {
7 7 School.Student std = new School.Student();
8 class Course 8 School.Course cs = new School.Course();
9 { 9 }
10 10 }
11 } 11 }
12 }

 Classes under the same namespace can be referred to as namespace.classname syntax.


 For example, the Student class can be accessed as School.Student.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 9
Namespaces Cont..
 To use classes under a namespace without the fully qualified name, import the namespace
with the using keyword at the top of C# class file.
Example: Namespace Example: Namespace
1 using System; //built-in namespace 1 namespace School
2 using School; 2 {
3 3 class Student
4 namespace DUDemo 4 {
5 { 5
6 class Program 6 }
7 { 7
8 static void Main(string[] args) 8 class Course
9 { 9 {
10 Student std = new Student(); 10
11 } 11 }
12 } 12 }
13 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 10
How to Create a Console Application?
 To create a new application in visual studio, go to the Menu bar, select File  New  select
a Project like as shown below.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 11
How to Create a Console Application? Cont..
 Once you click on the OK button, a new console application will be created like as shown
below.
 In case the Program.cs file not opened in your code editor, open Solution Explorer menu on
the right side and open your Program.cs file code by double-clicking If
it. you observe the
above image, by default
the application contains
a Main() method.
Because the console
applications in the C#
programming
language will always
start from
the Main() method of
the Program class.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 12
Hello World! In C#
Program.cs Output
1 using System;
2
3 namespace HelloWorld
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 // This is a comment.
10 Console.WriteLine("Hello World!");
11 Console.WriteLine("Press Enter Key to Exit.");
12 Console.ReadLine();
13 }
14 }
15 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 13
Explanation of C# Hello World Program

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 14
Explanation: C# Hello World Program
using System;
 Here, using System is the .NET Framework library namespaces, and we used using keyword to import system namespace to
use existing class methods such as WriteLine(), ReadLine(), etc.
 By default, the .NET Framework provides a lot of namespaces to make the application implementation easy.

namespace HelloWorld
 Here, namespace HelloWorld is the main namespace of our application, and by default, our application classes will be a part
of it.
class Program
 Here, class Program is used to define a class (Program) in the namespace (Helloworld).
 The class (Program) will contain all the variables, methods, etc., and we can define more than one class in same namespace
based on our requirements.
static void Main(string[] args)
 The keyword static tells us that the main method can be accessible without instantiating the class (Program).
 Another keyword void tells us that what this method should return.
 The name Main will refer to the name of our class method (Program). The Main() method is the entry point of our console
application.
 Here, Console.WriteLine() and Console.ReadLine() methods are used to write a text to the console and read the input from
the console.
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 15
Compile and Run C# Hello World Program
 To see Program's output, you need to compile and run the application by pressing either Ctrl
+ F5 or click on the Start option in the menu bar like as shown below.

 Once you click on the Start option or Ctrl + F5, our program will get compiled and show the
result as shown below.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 16
Console.WriteLine() and Console.Write() in C#
 The Console.WriteLine() and Console.Write() methods print values or texts to the console.
 Console.WriteLine() method prints a new line after the text or a value.
 Console.Write() method only prints the text or value without a new line.
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 Console.Write("Welcome to");
9 Console.Write(" Darshan University");
10 Console.WriteLine("\n-------------------");
11 Console.WriteLine("Welcome to ");
12 Console.WriteLine("Darshan University");
13 Console.ReadLine();
14 }
15 }
16 }
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 17
Difference: ReadLine(), Read(), ReadKey() in C#
 Console.ReadLine()
 Reads the next line of characters from the standard input stream.
 Simply you can say, it read all the characters from user input. (and finish when press enter).
 It return a STRING so data type should be STRING.
 It means it reads all characters until the end of line.
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 string name = Console.ReadLine();
9 Console.WriteLine("ReadLine Result
10 is :"+name);
11 }
12 }
}

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 18
Difference: ReadLine(), Read(), ReadKey() in C# Cont..
 Console.Read()
 Reads the next character from the standard input stream.
 It only accept single character from user input and return its ASCII Code.
 Data type should be int, because it return an integer value as ASCII.
 As we input "6" and it return its ASCII value "54".
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 int val = Console.Read();
9 Console.WriteLine("Read Result is :"+val);
10 }
11 }
12 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 19
Difference: ReadLine(), Read(), ReadKey() in C# Cont..
 Console.ReadKey()
 It obtains the next character or function key pressed by the user.
 In simple words, it read that which key is pressed by user and return its name.
 It does not require to press enter key before entering.
 It is STRUCT Data type which is ConsoleKeyInfo.
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
{
7
while (true)
8 {
9 ConsoleKeyInfo key = Console.ReadKey();
10 Console.WriteLine("\n You pressed " + key.Key);
11 }
12 }
13 }
14 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 20
Data Types & Variables
Section - 3
Data Types
 In c# programming language, Data Types are useful to define a type of data the variable can
hold, such as integer, float, string, etc., in our application.
 C# is a Strongly Typed programming language.
 Before we perform any operation on variables, it’s mandatory to define a variable with the
required data type to indicate what type of data that variable can hold in our application.
 Syntax of Defining C# Data Types
[Data Type] [Variable Name];
[Data Type] [Variable Name] = [Value];
 If you observe the above syntax, we added a required data type before the variable name to
tell the compiler about what type of data the variable can hold or which data type the variable
belongs to.
 [Data Type] - It’s a type of data the variable can hold, such as integer, string, decimal, etc.
 [Variable Name] - It’s the name of the variable to hold the values in our application.
 [Value] - Assigning a required value to the variable.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 22
Example: Data Types
Program.cs Output
1 using System;
2
3 namespace MyFirstApp
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 int number = 10;
10 string name = "Darshan University";
11 double percentage = 10.23;
12 char gender = 'M';
13 bool isVerified = true;
14
15 Console.WriteLine(number);
16 Console.WriteLine(name);
17 Console.WriteLine(percentage);
18 Console.WriteLine(gender);
19 Console.WriteLine(isVerified);
20 Console.ReadLine();
21 }
22 }
23 }
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 23
Rules to Declare C# Variables
 Before we declare and define variables in the c# programming language, we need to follow
particular rules.
 You can define a variable name with a combination of alphabets, numbers, and underscore.
 A variable name must always start with either alphabet or underscore but not with numbers.
 While defining the variable, no white space is allowed within the variable name.
 Don't use any reserved keywords such as int, float, char, etc., for a variable name.
 In c#, once the variable is declared with a particular data type, it cannot be re-declared with a new type,
and we shouldn’t assign a value that is not compatible with the declared type.
Valid Invalid
1 int abc; 1 int a b c;
2 float a2b; 2 float 2abc;
3 char _abc; 3 char &abc;
4 int a,b,c; 4 double int;
5 float x, y, z = 10.5;

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 24
Guess the Output???
Program.cs Output
1 using System;
2
3 namespace Variables
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 int x = 7;
10 string y = "5";
11 string myFirstTry = x.ToString() + y;
12 int mySecondTry = x + int.Parse(y);
13 Console.WriteLine(myFirstTry);
14 Console.WriteLine(mySecondTry);
15 Console.ReadLine();
16 }
17 }
18 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 25
Operators
Section - 4
Operators
 Operators in C# are some special symbols that perform some action on
operands.
 In mathematics, the plus symbol (+) do the sum of the left and right numbers. In
the same way, C# includes various operators for different types of operations.
 The following example demonstrates the + operator in C#.
Example
1 int x = 5 + 5;
2 int y = 10 + x;
3 int z = x + y;

 In the above example, + operator adds two number literals and assign the result
to a variable.
 It also adds the values of two int variables and assigns the result to a variable.
 Some operators behave differently based on the type of the operands. For
example,
1 string +greet1
operator concatenates
= "Hello two strings.
" + "World!";

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 27
Type of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 28
A =10,
1. Arithmetic Operators B=20
Operator Description Example
+ Adds two operands A + B = 30
- Subtracts second operand from the first A - B = -10
* Multiplies both operands A * B = 200
/ Divides numerator by de-numerator B/A= 2
% Modulus Operator and remainder of after an integer division B %A= 0
++ Increment operator increases integer value by one A++ = 11
-- Decrement operator decreases integer value by one A-- = 9

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 29
Example: Arithmetic Operators
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 int ans;
9 int x = 20, y = 10;
10 ans = (x + y);
11 Console.WriteLine("Addition Operator: " + ans);
12 ans = (x - y);
13 Console.WriteLine("Subtraction Operator: " + ans);
14 ans = (x * y);
15 Console.WriteLine("Multiplication Operator: " + ans);
16 ans = (x / y);
17 Console.WriteLine("Division Operator: " + ans);
18 ans = (x % y);
19 Console.WriteLine("Modulo Operator: " + ans);
20 ans = (x++);
21 Console.WriteLine("Increment Operator: " + ans);
22 ans = (x--);
23 Console.WriteLine("Decrement Operator: " + ans);
24 Console.ReadLine();
25 }
26 }
27 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 30
A =10,
2. Relational Operators B=20
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
Checks if the values of two operands are equal or not, if values are not equal then condition
!= (A != B) is true.
becomes true.
Checks if the value of left operand is greater than the value of right operand, if yes then
> (A > B) is not true.
condition becomes true.
Checks if the value of left operand is less than the value of right operand, if yes then
< (A < B) is true.
condition becomes true.
Checks if the value of left operand is greater than or equal to the value of right operand, if
>= (A >= B) is not true.
yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of right operand, if yes
<= (A <= B) is true.
then condition becomes true.
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 31
Example: Relational Operators
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 int a = 21, b = 10;
9 if (a == b)
10 Console.WriteLine("a is equal to b");
11 else
12 Console.WriteLine("a is not equal to b");
13 if (a < b)
14 Console.WriteLine("a is less than b");
15 else
16 Console.WriteLine("a is not less than b");
17 if (a > b)
18 Console.WriteLine("a is greater than b");
19 else
20 Console.WriteLine("a is not greater than b");
21 /* Lets change value of a and b */
22 a = 5; b = 20;
23 if (a <= b)
24 Console.WriteLine("a is either less than or equal to b");
25 if (b >= a)
26 Console.WriteLine("b is either greater than or equal to b");
27 }
28 }
29 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 32
3. Logical Operators
Operator Description Example
&& Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is false.
|| Logical OR Operator. If any of the two operands is non zero then condition becomes true. (A || B) is true.
Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true
! !(A && B) is true.
then Logical NOT operator will make false.

Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 bool a = true;
9 bool b = false;
10 Console.WriteLine(a && b);
11 Console.WriteLine(a || b);
12 Console.WriteLine(!(a && b));
13 Console.ReadLine();
14 }
15 }
16 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 33
A =60,
4. Bitwise Operators B=13
Operator Description Example
(A & B) = 12, which is 0000
& Binary AND Operator copies a bit to the result if it exists in both operands.
1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, which is 0011 0001
(~A ) = -61, which is 1100 0011
~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. in 2's complement due to a
signed binary number.
Binary Left Shift Operator. The left operands value is moved left by the number A << 2 = 240, which is 1111
<<
of bits specified by the right operand. 0000
Binary Right Shift Operator. The left operands value is moved right by the
>> A >> 2 = 15, which is 0000 1111
number of bits specified by the right operand.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 34
Example: Bitwise Operators
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 int a = 60; /* 60 = 0011 1100 */
9 int b = 13; /* 13 = 0000 1101 */
10 int c = 0;
11 c = a & b; /* 12 = 0000 1100 */
12 Console.WriteLine("Value of c is {0}", c);
13 c = a | b; /* 61 = 0011 1101 */
14 Console.WriteLine("Value of c is {0}", c);
15 c = a ^ b; /* 49 = 0011 0001 */
16 Console.WriteLine("Value of c is {0}", c);
17 c = ~a; /*-61 = 1100 0011 */
18 Console.WriteLine("Value of c is {0}", c);
19 c = a << 2; /* 240 = 1111 0000 */
20 Console.WriteLine("Value of c is {0}", c);
21 c = a >> 2; /* 15 = 0000 1111 */
22 Console.WriteLine("Value of c is {0}", c);
23
24 Console.ReadLine();
25 }
26 }
27 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 35
5. Assignment Operators
Operator Description Example
Simple assignment operator, Assigns values from right side operands to left side C = A + B assigns value of
=
operand A + B into C
Add AND assignment operator, It adds right operand to the left operand and assign C += A is equivalent to
+=
the result to left operand C=C+A
Subtract AND assignment operator, It subtracts right operand from the left operand C -= A is equivalent to
-=
and assign the result to left operand C = C -A
Multiply AND assignment operator, It multiplies right operand with the left operand C *= A is equivalent to
*=
and assign the result to left operand C = C *A
Divide AND assignment operator, It divides left operand with the right operand and C /= A is equivalent to
/=
assign the result to left operand C= C/A

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 36
Example: Assignment Operators
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 int a = 20;
9 int ans;
10 ans = a;
11 Console.WriteLine("= | Value of c = {0}", ans);
12 ans += a;
13 Console.WriteLine("+= | Value of c = {0}",
14 ans);
15 ans -= a;
16 Console.WriteLine("-= | Value of c = {0}",
17 ans);
18 ans *= a;
19 Console.WriteLine("*= | Value of c = {0}",
20 ans);
21 ans /= a;
22 Console.WriteLine("/= | Value of c = {0}",
23 ans);
Console.ReadLine();
}
}
}

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 37
Class & Objects
Section - 5
Class
 The class is like a blueprint of a specific object that has certain attributes and features.
 In c# class is nothing but a collection of various data members (fields, properties, etc.) and
member functions.
 Class is a data structure, and it will combine various types of data members such as fields,
properties, member functions, and events into a single unit.
 For example,
 A car should have some attributes such as four wheels, two or more doors, steering, a windshield, etc.
 It should also have some functionalities like start, stop, run, move, etc.
 Now, any object that has these attributes and functionalities is a car.
 It defines the kinds of data and the functionality their objects will have.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 39
Declaring a Class in C#
Class Declaration
1 public class users
2 {
3 // Properties, Methods, Events, etc.
4 }

 We defined a class “users” using class keyword with public access modifier.
 Here, the public access specifier will allow the users to create objects for this class, and
inside of the body class, we can create required fields, properties, methods, and events for
specific usage.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 40
Objects of a Class
 Objects are real-world entities and instance of a class.
 For example, chair, car, pen, mobile, laptop etc.
 We can create one or more objects of a class.
 Each object can have different values of properties and field but, methods and events behaves
the same.
Create Multiple
Object Creation
Objects
1 Student student1 = new Student(); 1 Student student1 = new Student();
2 student1.FirstName = "Raj";
Access Members of a Class 3 student1.LastName = "Mehta";
1 Student student1 = new Student(); 4
2 5 Student student2 = new Student();
3 student1.FirstName = "Naimish"; 6 student2.FirstName = "Abhay";
4 student1.LastName = "Patel"; 7 student2.LastName = "Doshi";
5
6 student1.GetFullName();

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 41
Example: Class & Object
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 public class Users
5 {
6 public int id = 0;
7 public string name = string.Empty;
8
9 public void GetUserDetails()
10 {
11 Console.WriteLine("Enter your user id:");
12 id = int.Parse(Console.ReadLine());
13 Console.WriteLine("Enter your name:");
14 name = Console.ReadLine();
15 Console.WriteLine("Id: {0}, Name: {1}", id, name);
16 Console.ReadLine();
17 }
18 }
19
20 class Program
21 {
22 public static void Main(string[] args)
23 {
24 Users user = new Users();
25 user.GetUserDetails();
26 }
27 }
28 }
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 42
Example: Class & Object
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 public class Users
5 {
6 public int id = 0;
7 public string name = string.Empty;
8
9 public void GetUserDetails()
10 {
11 Console.WriteLine("Enter your user id:");
12 id = int.Parse(Console.ReadLine());
13 Console.WriteLine("Enter your name:");
14 name = Console.ReadLine();
15 Console.WriteLine("Id: {0}, Name: {1}", id, name);
16 Console.ReadLine();
17 }
18 }
19
20 class Program
21 {
22 public static void Main(string[] args)
23 {
24 Users user = new Users();
25 user.GetUserDetails();
26 }
27 }
28 }
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 43
Constructor
Section - 6
Constructor
 A constructor is a special type of method which will be called automatically when you create
an instance of a class.
 A constructor is defined by using an access modifier and class name
<access-modifier> <class-name>(){ }.
Example Constructor
1 public class Student  A constructor name Characteristics
must be the same as a class
2 {
name.
3 public Student()
4 {  A constructor can be public, private, or protected.
5 //constructor  The constructor cannot return any value so, cannot
6 } have a return type.
7 }  A class can have multiple constructors with different
parameters but can only have one parameter less
constructor.
 If no constructor is defined, the C# compiler would
create it internally.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 45
Type of Constructor
 Constructors can be classified as follows.
 Default Constructor
 By default, C# creates default constructor internally.
 Parameterized Constructor
 When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to
the constructor function.
 Copy Constructor
 The copy constructor is a constructor which creates an object by initializing it with an object of the same class,
which has been created previously.
 The copy constructor is used to: Initialize one object from another of the same type.
 Copy an object to pass it as an argument to a function.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 46
Example: Constructor
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 Users user = new Users("Naimish", 30);
9 user.GetUserDetails();
10 Console.ReadLine();
11 }
12 }
13 public class Users
14 {
15 public string Name = string.Empty;
16 public int Age = 0;
17 public Users(string name, int age) //Parameterized Constructor
18 {
19 Name = name;
20 Age = age;
21 }
22 public void GetUserDetails()
23 {
24 Console.WriteLine("Name: {0}, Age: {1}", Name, Age);
25 }
26 }
27 }
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 47
Example: Copy Constructor
Example
1 using System;
2 namespace MyFirstApp
3 {
4 public class Users
5 {
6 public string Name = string.Empty;
7 public int Age = 0;
8
9 public Users(string name, int age) //Parameterized Constructor
10 {
11 Name = name;
12 Age = age;
13 }
14
15 public void GetUserDetails()
16 {
17 Console.WriteLine("Name: {0}, Age: {1}", Name, Age);
18 }
19
20 public Users(Users user) //Copy Constructor
21 {
22 this.Name = user.Name;
23 this.Age = user.Age;
24 }
25 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 48
Example: Copy Constructor
Example Output
28 class Program
29 {
30 public static void Main(string[] args)
31 {
32 Users user1 = new Users("Naimish", 30);
33 Users user2 = new Users(user1);
34 user2.GetUserDetails();
35 Console.ReadLine();
36 }
37 }
38 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 49
Collection Classes
Section - 7
What is Collections?
 We mostly use arrays to store and manage data.
 However, arrays can store a particular type of data, such as integer and
characters.
 To resolve this issue, the .NET framework introduces the concept of collections
for data storage and retrieval, where collection means a group of different types
of data.
 Collections are similar to arrays, it provide a more flexible way of working with
a group of objects.
 In arrays, you need to define the number of elements at declaration time.
 But in a collection, you don't need to define the size of the collection in
advance. You can add elements or even remove elements from the collection at
any point of time.
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 51
Collection Classes
 The .NET Framework provides you a variety of collection classes, which are
available in the System.Collections namespace.
 Most useful collection classes defined are as follows.
 ArrayList Class
 Stack Class
 Queue Class
 Hashtable Class
 SortedList Class
 BitArray Class

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 52
ArrayList Class
 Using an arrays, the main problem arises is that their size always remain fixed by the number
that you specify when declaring an arrays.
 In addition, you cannot add items in the middle of array.
 Also you can not deal with different data types.
 The solution to these problems is the use of ArrayList Class.
 Similar to an array, the ArrayList class allows you to store and manage multiple elements.
 With the ArrayList class, you can add and remove items from a list of array items from a
specified position, and then the array items list automatically resizes itself accordingly.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 53
Example – ArrayList Class
using System;
Output :
using System.Collections;

namespace MyFirstApp
{
class Program
{
static void Main(string[]
args)
{
ArrayList A1 = new
ArrayList();
A1.Add(10);
A1.Add("Hello");
A1.Add(true);
Console.WriteLine(A1[0]);
Console.WriteLine(A1[1]);
Console.WriteLine(A1[2]);
Console.ReadLine();
}
}
} Prof. Naimish R. Vadodariya
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
54
Example – ArrayList Class
using System;

using System.Collections;
Output :

namespace MyFirstApp

class Program

static void Main(string[] args)

ArrayList A1 = new ArrayList();

A1.Add(10); A1.Add("Hello"); A1.Add(true);

Console.WriteLine(A1.Count);

Console.WriteLine(A1.Contains(10));

Console.WriteLine("-------------------");

Console.WriteLine(A1[1]);

A1.RemoveAt(1);

Console.WriteLine(A1[1]);

Console.ReadLine();

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 55
Stack Class
 The stack class represents a last in first out (LIFO) concept.
 let's take an example. Imagine a stack of books with each book kept on top of each other.
 The concept of last in first out in the case of books means that only the top most book can be
removed from the stack of books.
 It is not possible to remove a book from between, because then that would disturb the setting
of the stack.
 Hence in C#, the stack also works in the same way.
 Elements are added to the stack, one on the top of each other.
 The process of adding an element to the stack is called a push operation.
 The process of removing an element from the stack is called a pop operation.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 56
Example – Stack Class (Push)
using System;
using System.Collections; Output :

namespace MyFirstApp
{
class Program
{
public static void Main(string[] args)
{
Stack st = new Stack();
st.Push(1);
st.Push(2);
st.Push(3);

foreach (Object obj in st)


{
Console.WriteLine(obj);
}
Console.WriteLine("Total elements in the stack " +
st.Count);
Console.WriteLine("Stack contain element 3? " +
st.Contains(3));
Console.ReadLine();
}
}
}
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 57
Example – Stack Class (Pop)
using System;

using System.Collections; Output :

namespace MyFirstApp

class Program

public static void Main(string[] args)

Stack st = new Stack();

st.Push(1);

st.Push(2);

st.Push(3);

st.Pop();

foreach (Object obj in st)

Console.WriteLine(obj);

Console.ReadLine();

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 58
Queue Class
 The Queue class represents a first in first out (FIFO) concept.
 let's take an example. Imagine a queue of people waiting for the bus.
 Normally, the first person who enters the queue will be the first person to enter the bus.
 Similarly, the last person to enter the queue will be the last person to enter into the bus.
 The process of adding an element to the queue is the Enqueue operation.
 The process of removing an element from the queue is the Dequeue operation.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 59
Example – Queue Class (Enqueue)
using System;
using System.Collections;
Output :
namespace MyFirstApp
{
class Program
{
public static void Main(string[] args)
{
Queue qt = new Queue();
qt.Enqueue(1);
qt.Enqueue(2);
qt.Enqueue(3);
foreach (Object obj in qt)
{
Console.WriteLine(obj);
}
Console.WriteLine("Total elements in the
queue =" + qt.Count);
Console.WriteLine("Queue contain element 3?
" + qt.Contains(3));
Console.ReadLine();
}
}
} #2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 60
Example – Queue Class (Dequeue)
using System;

using System.Collections;
Output :
namespace MyFirstApp

class Program

public static void Main(string[] args)

Queue qt = new Queue();

qt.Enqueue(1);

qt.Enqueue(2);

qt.Enqueue(3);

qt.Dequeue();

foreach (Object obj in qt)

Console.WriteLine(obj);

Console.ReadLine();

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 61
Hashtable Class
 The Hashtable class is similar to the ArrayList class, but it allows you to access the items by a
key.
 Each item in a Hashtable object has a key/value pair.
 So instead of storing just one value like the stack, array list and queue, the Hashtable stores 2
values that is key and value.
 The key is used to access the items in a collection and each key must be unique, whereas the
value is stored in an array.
 The keys are short strings or integers.
 There is no direct way to display the elements of a Hashtable.
• { "1" , “Darshan" }
• { "2" , “Institute " }
• { "3" , "of Engg. & Technology" }
 This is done via the ICollection interface. (This is a special data type which can be used to store the
keys of a Hashtable collections)
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 62
Example – Hashtable Class
using System;

using System.Collections;
Output :
namespace MyFirstApp

class Program

public static void Main(string[] args)

Hashtable ht = new Hashtable();

ht.Add("1", "Darshan");

ht.Add("2", "Institute");

ht.Add("3", "of Engg. & Technology");

ICollection keys = ht.Keys;

foreach (String k in keys)

Console.WriteLine(ht[k]);

Console.ReadLine();

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 63
SortedList Class
 The SortedList class is a combination of the array and hashtable classes.
 The SortedList<TKey, TValue>, and SortedList are collection classes that can store key-value
pairs that are sorted by the keys based on the associated IComparer implementation.
 For example, if the keys are of primitive types, then sorted in ascending order of keys.
 C# supports generic and non-generic SortedList.
 It is recommended to use generic SortedList<TKey, TValue> because it performs faster and
less error-prone than the non-generic SortedList.
 SortedList Characteristics
 SortedList<TKey, TValue> is an array of key-value pairs sorted by keys.
 Sorts elements as soon as they are added. Sorts primitive type keys in ascending order and object keys
based on IComparer<T>.
 It comes under System.Collection.Generic namespace.
 A key must be unique and cannot be null but a value can be null or duplicate.
 A value can be accessed by passing associated key in the indexer mySortedList[key]

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 64
Example – SortedList Class
using System; //The following will throw exceptions

using System.Collections; //numberNames.Add("Three", 3); //Compile-time error: key must


be int type

//numberNames.Add(1, "One"); //Run-time exception: duplicate


namespace MyFirstApp key

{ //numberNames.Add(null, "Five");//Run-time exception: key


cannot be null
class Program
foreach (var vr in numberNames)
{
{
public static void Main(string[] args)
Console.WriteLine("key: {0}, value: {1}", vr.Key, vr.Value);
{
}
//SortedList of int keys, string values
}
SortedList<int, string> numberNames = new
SortedList<int, string>(); }

numberNames.Add(3, "Three"); }

numberNames.Add(1, "One"); Output :


numberNames.Add(2, "Two");

numberNames.Add(4, null);

numberNames.Add(10, "Ten");

numberNames.Add(5, "Five");

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 65
BitArray Class
 The BitArray class is used to manage an array of the binary representation using the value 1
and 0, where 1 stands for true and 0 stands for false.
 A BitArray object is resizable, which is helpful in case if you do not know the number of bits
in advance.
 You can access items from the BitArray collection class by using an integer index.
 A BitArray can be used to perform Logical AND, XOR, OR operations.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 66
Example – BitArray Class
using System;

using System.Collections;
Output :
namespace MyFirstApp

class Program

public static void Main(string[] args)

BitArray ba = new BitArray(4);

ba[0] = true;

ba[1] = false;

ba[2] = true;

ba[3] = false;

foreach (Object obj in ba)

Console.WriteLine(obj);

Console.ReadLine();

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 67
Inheritance
Section - 8
Intro: Inheritance

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 69
Intro: Inheritance
 Inheritance is where one class (child class) inherits the properties of another
class (parent class).
 Inheritance is a mechanism of acquiring the features and behaviors of a class by
another class.
 The class whose members are inherited is called the base class, and the class
that inherits those members is called the derived class.
 Inheritance implements the IS-A relationship.
 Example
 “She had inherited the beauty of her mother”
 Why Inheritance?
 Reduce code redundancy
 Provides code reusability
 Reduces source code size and improves code readability
 Code is easy to manage and divided into parent and child classes
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 70
Types of Inheritance

Single Inheritance

Multi-level Inheritance

Multiple Inheritance

Multipath Inheritance

Hierarchical Inheritance

Hybrid Inheritance
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 71
Single Inheritance

Class A (Base)
Single Inheritance
In single inheritance, a
derived class is created from a
single base class.
Class B (Derived)

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 72
Example - Single Inheritance

//Base Class //Derived Class


class Teacher class Student : Teacher
{ {
public void Teach() public void Learn()
{ {
Console.WriteLine("Teach"); Console.WriteLine("Learn");
} }
} }

class Program
{
static void Main(string[] args)
{
Teacher d = new Teacher();
d.Teach();
Student s = new Student();
s.Learn();
s.Teach();
Console.ReadKey();
}
}

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 73
Multi-level Inheritance

Class A (Base)
Multi-level
Inheritance
In Multi-level inheritance, a
Class B derived class is created from
another derived class.

Class C

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 74
Example – Multi-Level Inheritance

//Base,Derived Class
//Base Class
class Student : Teacher
class Teacher
{
{
public void Learn()
public void Teach()
{
{
Console.WriteLine("Teach");
Console.WriteLine("Learn");
}
}
}
}

class Program
{
static void Main(string[] args)
//Derived Class {
Teacher d = new Teacher();
class SemFour : Student d.Teach();
{
Student s = new Student();
public void FourthSem() s.Learn();
{ s.Teach();

Console.WriteLine("Semester SemFour Sem = new SemFour();


Sem.Learn();
Four Students"); Sem.Teach();
} Sem.FourthSem();
} Console.ReadKey();
}
}

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 75
Multiple Inheritance

Class A (Base) Class B (Base)

Class C

Multiple Inheritance
 In Multiple inheritance, a derived class is created from more than
one base class.
 This type of inheritance is not supported by .NET Languages
like C#, F# etc.
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 76
Example – Multiple Inheritance

//Base Class //Base,Derived Class


class Teacher class Student
{ {
public void Teach() public void Learn()
{ {
Console.WriteLine("Teach"); Console.WriteLine("Learn");
} }
} }

//Derived Class
class SemFour : Student , Teacher
{
public void FourthSem()
{
Console.WriteLine("Semester
Four Students");
}
}

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 77
Multipath Inheritance

Class A

Class B Class C

Class D

Multipath Inheritance
 In Multipath inheritance, a derived class is created from another
derived classes and the same base class of another derived classes.
 This type of inheritance is not supported by .NET Languages
like C#, F# etc.
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 78
Example – Multipath Inheritance

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 79
Hierarchical Inheritance

Class A

Class C Class B

Class D Class E Class F Class G

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 80
Example – Hierarchical Inheritance

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 81
Hybrid Inheritance

Class A Class F

Class C Class B

Class D Class E

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 82
Example – Hybrid Inheritance

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 83
String
Section - 9
String: Introduction
 In C#, string is another kind of data type that represents Unicode Characters.
 It is the alias of System.String however, you can also write System.String instead of string.
 Technically there is no difference between them and you can use any of them.
 String is a class name whereas string is a reserved keyword.
 You should always use string instead of String.
 It is the sequence of character in which each character is a Unicode character.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 85
String Methods string firstname = "Steven Clark";
string lastname = "Clark";

Functions Description
// Make String Clone
Clone() Console.WriteLine(str1.Clone());
//Compare two string value and returns 0 for true and 1 for false
CompareTo() Console.WriteLine(str1.CompareTo(lastname));
//Check whether specified value exists or not in string
Contains() Console.WriteLine(str1.Contains("ven"));
//Check whether specified value is the last character of string
EndsWith() Console.WriteLine(str1.EndsWith("n"));
//Compare two string and returns true and false
Equals() Console.WriteLine(str1.Equals(lastname));
//Returns the first index position of specified value the first index
IndexOf() position of specified value
Console.WriteLine(str1.IndexOf("e"));

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 86
String Methods Cont.. string firstname = "Steven Clark";
string lastname = "Clark";

Functions Description
//Covert string into lower case
ToLower() Console.WriteLine(str1.ToLower());
//Convert string into Upper case
ToUpper() Console.WriteLine(str1.ToUpper());
//Insert substring into string
Insert() Console.WriteLine(str1.Insert(0, "Hello"));
//Returns the last index position of specified value
LastIndexOf() Console.WriteLine(str1.LastIndexOf("e"));
//Returns the Length of String
Length Console.WriteLine(str1.Length);
//Deletes all the characters from begining to specified index.
Remove() Console.WriteLine(str1.Remove(5));
// Replace the character
Replace() Console.WriteLine(str1.Replace('e', 'i'));

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 87
String Methods Cont.. string firstname = "Steven Clark";
string lastname = "Clark";

Functions Description
//Check wheater first character of string is same as specified value
StartsWith() Console.WriteLine(str1.StartsWith("S"));
//Returns substring
Substring() Console.WriteLine(str1.Substring(2, 5));
//It removes starting and ending white spaces from string.
Trim() Console.WriteLine(str1.Trim());

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 88
Debugging and Error Handling
Section - 10
Debugging and Error Handling
 Exception is a runtime error that arises because of some abnormal conditions, such as
division of a number by zero and passing a string to a variable that holds an integer value.
 Capturing and handling of runtime error is one of the important and crucial tasks for any
programmer.
 Compile time errors are those errors that occur during the compilation of a program.
 It can happen due to bad coding or incorrect syntax.
 We can correct these compile time errors after looking at the error message that the compiler
generates.
 On the other hand, runtime errors are those errors that occur during the execution of a
program, and thus, they cannot be corrected at that time.
 So, necessary actions need to be taken beforehand to prevent such types of errors.
 To do so, you should first identify the following two aspects.
 Find out those parts of a program which can cause runtime errors
 How to handle those errors when they occur
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 90
Exception Classes
Class Description
SystemException Represents a base class for other exception classes
DivideByZeroException Occurs if you try to divide a number by zero
IndexOutOfRangeException Occurs if the index of an array is out of bound
FormatException Occurs if there is an incorrect format of argument
OutOfMemoryException Occurs if an execution stops due to lake of memory
StackOverflowException Occurs if a stack overflows

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 91
Exception Handling
 Exceptions can be handled by using the  try
following two statements.  The try block encloses the statements that
 The try…catch…finally statement might throw an exception.
 The throw statement  catch
 The catch block handles the exceptions
try block thrown by the try block.
 In a program, a try block can contain one or
multiple catch blocks.
Code Yes  finally
throws an catch block
exception  It is an optional block and is always
executed.
No  If no exception occurs inside the try block,
All Errors Processed
finally block the program control is transferred
directly to the finally block.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 92
Example: Exception Handling
using System;
Output :
namespace MyFirstPrg

class Program

static void Main(string[] args)

int number = 0;

int div = 0;

try

div = 100 / number;

catch (DivideByZeroException)

Console.WriteLine("Exception Occured");

Console.WriteLine("Result is : " + div);

Console.ReadLine();

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 93
The throw Statement
 The throw statement is used to raise an exception in case an error occurs in a program.
 It is also possible to throw an exception programmatically.
try
{
throw new DivideByZeroException();
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception :" + e);
}

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 94
Example: throw statement
using System;
finally
namespace MyFirstPrg {
{ Console.WriteLine("This is the last statement");
class Program Console.ReadLine();
{ }
static void Main(string[] args) }
}
{
}
Console.WriteLine("Enter a Number");

int number = int.Parse(Console.ReadLine());

try Output :
{

if (number > 10)

throw new Exception("Maximum Limit is 10");

catch (Exception e)

Console.WriteLine("Exception has been occured");

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 95
Method Overloading
Section - 11
Method Overloading
 Function overloading (method overloading) is a programming concept that allows
programmers to define two or more functions with the same name.
 C# also allows us to define multiple functions with the same name differing in the argument
type and order of arguments. This is termed as method overloading.
 There is no need to use any keyword while overloading a function or method either in same
class or in derived class.
 While overloading functions or methods, you have to follow the rules that overloaded
methods must differ either in number of arguments or the data type of at least one argument.
 In case of function or method overloading, compiler identifies which overloaded method to
execute based on number of arguments and their data types during compilation itself.
 Hence method overloading is an example for compile time polymorphism.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 97
Function (Method) Overloading

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 98
Example: Method Overloading
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 Add sum = new Add();
9 Console.WriteLine("Addtion is {0}",sum.add(2,3));
10 Console.WriteLine("Addtion is {0}",sum.add(2));
11 Console.ReadLine();
12 }
13 }
14 public class Add
15 {
16 public int add(int a, int b)
17 {
18 return a + b;
19 }
20 public int add(int a)
21 {
22 return a + a;
23 }
24 }
25 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 99
Method Overriding
Section - 12
Method Overriding
 Overriding can be defined as: being able to change the behavior of methods in classes, known
as overriding their logic.
 Method overriding is also known as runtime polymorphism.
 There are the following 3 types of keywords used in C# for method overriding:
 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.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 101
Example: Method Overriding
Example
1 using System;
2 namespace MyFirstApp
3 {
4 class baseClass
5
{
6
//Virtual Function (Overridable Method)
7
8 public virtual void Greetings()
9 {
10 Console.WriteLine("Greetings from baseClass!");
11 }
12 }
13 class subClass : baseClass
14 {
15 //Overriding Method
16 public override void Greetings()
17 {
18 //Calling Parent Class Method
19
base.Greetings();
20
Console.WriteLine("Greetings from subClass!");
21
22 }
23 }
24

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 102
Example: Method Overriding
Example Output
25 class Program
26 {
27 static void Main(string[] args)
28 {
29
subClass obj1 = new subClass();
30
obj1.Greetings();
31
32 Console.ReadLine();
33 }
34 }
35 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 103
Operator Overloading
Section - 13
Operator Overloading
 Each operator has predefined meaning most of them are given additional meaning through
the concept of Operator Overloading.
 ‘+’ is used for addition
 ‘+’ can not use for concatenation?
 String 1 = Ram & String 2 = Rahim
 We can not concat two strings using + operator like ‘Ram Rahim’??
 Overloaded operators are functions with special names the keyword operator followed by
the symbol for the operator being defined.
 Syntax
public static return-type operator op(arguments)
{

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 105
Operator Overloading
 When any operator is overloaded, its original meaning is not lost.
 Similar to any other function, an overloaded operator has a return type and a parameter list.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 106
Example: Operator Overloading
using System; public void ShowResult()
namespace Demo {
{ Console.WriteLine(a + "," + b + "," + c);
class calculation Console.ReadLine();
{ }
int a, b, c;
}
public calculation()
class Program
{ {
a = b = c = 0; static void Main(string[] args)
} {
public calculation(int x, int y, int z) calculation i = new calculation(10,20, 30);
{ i++;
a = x; i.ShowResult();
Console.ReadLine();
b = y;
}
c = z;
}
} }
public static calculation operator ++(calculation op1)
{ Output :
op1.a++;
op1.b++;
op1.c++;
return op1;
}

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 107
Access Modifiers
Section - 14
Access Modifiers
 Access modifiers are keywords used to specify the declared accessibility of a member or a
type.
 Why to use access modifiers?
 Access modifiers are an integral part of object-oriented programming.
 They support the concept of encapsulation, which promotes the idea of hiding functionality.
 Access modifiers allow you to define who does or doesn't have access to certain features.
 In C# Modifiers can be divided in five categories.
 Public
 Private
 Protected
 Internal
 Protected internal

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 109
Public Modifier
 Public members are accessible anywhere in program or application.
 Public access is the most permissive access level.
 There are no restrictions on accessing public members.
 The public keyword is used for it.

 Accessibility:
 Can be accessed by objects of the class
 Can be accessed by derived classes

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 110
Example: Public Modifier
Example Output
1 using System;
2 namespace Demo
3 {
4 class Access
5
{
6
public int num1;
7
8 }
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 Access ob1 = new Access();
14 //Direct access to public members
15 ob1.num1 = 100;
16 Console.WriteLine("Number one value in main {0}", ob1.num1);
17 Console.ReadLine();
18 }
19
}
20
}
21

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 111
Private Modifier
 Private members are accessible only within the body or scope of the class or the structure in
which they are declared.
 Private access is the least permissive access level.
 The private keyword is used for it.

 Accessibility:
 Cannot be accessed by object
 Cannot be accessed by derived classes

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 112
Example: Private Modifier
Example
1 using System;
2 namespace Demo
3 {
4 class Access
5
{
6
public int num1;
7
8 private int num2;
9 }
10 class Program
11 {
12 static void Main(string[] args)
13 {
14 Access ob1 = new Access();
15 //Direct access to public members
16 ob1.num1 = 100;
17 //Access to private member is not permitted
18 ob1.num2 = 10;
19
Console.WriteLine("Number one value in main {0}", ob1.num1);
20
Console.ReadLine();
21
22 }
23 } 'Access.num2' is inaccessible due to its protection level.
24 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 113
Protected Modifier
 A protected member is accessible from within the class in which it is declared and from
within any class derived from the class that declared this member.
 A protected member of a base class is accessible in a derived class only if the access takes
place through the derived class type.
 The protected keyword is used for it.

 Accessibility:
 Cannot be accessed by object
 By derived classes

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 114
Example: Protected Modifier
Example
1 using System;
2 namespace Demo
3 {
4 class Access
5
{
6
protected int num1;
7
8 }
9 class Program: Access
10 {
11 static void Main(string[] args)
12 {
13 Access access = new Access();
14 Program program = new Program();
15
16 //Access to protected member as it is inherited by derived class.
17 program.num1 = 20;
18
19
//Can not Access to protected member
20
access.num1 = 100;
21
22 Console.WriteLine("Number one value in main {0}", program.num1);
23 Console.ReadLine();
24 }
25 }
26 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 115
Internal Modifier
 We can declare a class as internal or its member as internal.
 Internal members are accessible only within the same assembly.
 In other words, access is limited exclusively to classes defined within the current project
assembly.
 The internal keyword is used for it.

 Accessibility:
 The variable or classes that are declared with internal can be access by any member within application.
 It is the default access specifiers for a class in C# programming.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 116
Example: Internal Modifier
Example Output
1 using System;
2
3 namespace First_Prg
4 {
5 class access
6 {
7 // String Variable declared as internal
8 internal string name;
9 public void print()
10 {
11 Console.WriteLine("\nMy name is " + name);
12 }
13 }
14 class Program
15 {
16 static void Main(string[] args)
17 {
18 access ac = new access();
19 Console.Write("Enter your name: ");
20 // Accepting value in internal variable
21 ac.name = Console.ReadLine();
22 ac.print();
23 Console.ReadLine();
24 }
25 }
26 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 117
Protected Internal Modifier
 The protected internal accessibility means protected OR internal, not protected AND
internal.
 In other words, a protected internal member is accessible from any class in the same
assembly, including derived classes.
 The protected internal access specifier allows its members to be accessed in derived class,
containing classes within same application.

 Accessibility:
 Within the class in which they are declared
 Within the derived classes of that class available within the same assembly
 Outside the class within the same assembly
 Within the derived classes of that class available outside the assembly

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 118
Example: Protected Internal Modifier
Example Output
1 using System;
2
3 namespace First_Prg
4 {
5 class access
6 {
7 // String Variable declared as protected internal
8 protected internal string name;
9 public void print()
10 {
11 Console.WriteLine("\nMy name is " + name);
12 }
13 }
14 class Program
15 {
16 static void Main(string[] args)
17 {
18 access ac = new access();
19 Console.Write("Enter your name: ");
20 // Accepting value in internal variable
21 ac.name = Console.ReadLine();
22 ac.print();
23 Console.ReadLine();
24 }
25 }
26 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 119
Default Access
 A default access level is used if no access modifier is specified in a member declaration.
 The following list defines the default access modifier for certain C# types:

C# Types Description
enum The default and only access modifier supported is public.
Class The default access for a class is private.
It may be explicitly defined using any of the access modifiers.

Interface The default and only access modifier supported is public.


Struct The default access is private with public and internal supported as well.

Interface and enumeration members are always public and no access modifiers are allowed.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 120
Delegates
Section - 16
Delegates
 A delegate is a type that represents references to methods with a particular parameter list
and return type.
 When we instantiate a delegate, we can associate its instance(object) with any method with a
compatible signature and return type.
 You can invoke (or call) the method through the delegate instance(object).
 Delegates are used to pass methods as arguments to other methods.
 In delegates, the signature does include the return value. Means a method must have the
same return type as the delegate.
 Syntax:

access-modifiers delegate return-type DelegateName(parameters);

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 122
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 123
Properties
Section - 15
Properties
 In C#, properties are nothing but natural extension of data fields.
 They are usually known as 'smart fields' in C# community.
 We know that data encapsulation and hiding are the two fundamental characteristics of any
object oriented programming language.
 In C#, data encapsulation is possible through either classes or structures.
 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.
 Properties are special kind of class member, In properties we use predefined Set and Get
method.
 They use assessors through which we can read, written or change the values of the private
fields.
 We cannot access these fields from outside the class , but we can accessing these private
fields through properties

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 125
Properties Cont..
 A property is a combination of variable and a method.
 A property is used to provide a flexible way to read, write, or change values of a private field.
 The get method is used to return property value to the user.
 The set method is used to assign a new value to the property.
 Syntax

Public <return type> <PropertyName>


{
get
{
return <var>;
}
set
{
<var> = value;
}
}

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 126
Example - Properties
class Example class Program
{ {
private int number; static void Main(string[] args)
{
public int Number
Example example = new Example();
{
// set { }
get
example.Number = 5;
{ // get { }
return number; Console.WriteLine(example.Number);
} Console.Read();
set }
}
{
number = value;
}
Output :
}
} 5

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 127
Indexers
Section - 16
Indexers
 Indexer is a new concept introduced by C#.
 An Indexer is a special type of property that allows a class or structure to be accessed the
same way as array for its internal collection.
 It is same as property except that it defined with this keyword with square bracket and
parameters.
 It can be used for overloading a [ ] operator.
Syntax :
public <return type> this [argument list]
{
get
{
//code for get
}
set
{
//code for get
}
}
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 129
Example: Indexers
class sample class Program
{ {
private string[] name = new string[3];
static void Main(string[] args)
public string this[int index]
{ {
get sample s = new sample();
{ s[0] = "Darshan";
if (index < 0 || index >= name.Length) s[1] = "Institute";
return null; s[2] = "Of Engg. & Tech.";
else
for (int i = 0; i <= 2; i++)
return name[index];
} {
Console.WriteLine(s[i]);
set }
{ Console.ReadKey();
name[index] = value; }
} }
}
} Output :
Darshan
Institute
Of Engg. & Tech.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 130
Properties v/s Indexers

Properties Indexers

Properties don't require this keyword Indexers are created with this keyword

Properties are identified by their names Indexers are identified by signature

Properties are accessed by their names Indexers are accessed using indexes
Properties are also known as the smart fields Indexers are also known as smart arrays

A get accessor of a property has no parameters & A Indexers in C# must have atleast one parameter &
set accessor of a property contains the implicit value it also supports more than one different types of
parameter. parameters

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 131
Properties v/s Indexers
Properties Indexers
Syntax of Properties Syntax of Indexers
<access_modifier> <return_type> <access_modifier> <return type> this [argument
<property_name> list]
{ {
get get
{ {
// Get codes goes here // Get codes goes here
} }
set set
{ {
// Set codes goes here // Set codes goes here
} }
} }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 132
Abstraction
Section - 17
Abstraction
 Data abstraction is the process of hiding certain details and showing only essential
information to the user.
 Abstraction can be achieved with either abstract classes or interfaces.
 The abstract keyword is used for classes and methods:
 Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited
from another class).
 Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided
by the derived class (inherited from).
 An abstract class can have both abstract and regular methods.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 134
Example: Abstraction
Example
1 using System; 24 class program
2 25 {
3 namespace First_Prg 26 static void Main(string[] args)
4 { 27 {
5 28
abstract class animal dog mydog = new dog();
6 29
{ animal thePet = mydog;
7 30
8 public abstract void eat(); thePet.eat();
31
9 public void sound() 32 mydog.sound();
10 { 33 }
11 Console.WriteLine("dog can sound"); 34 }
12 } 35 }
13 }
14 class dog : animal
15 {
16 public override void eat() Output
17 {
18 Console.WriteLine("dog can eat");
19
}
20
}
21

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 135
Interface
Section - 18
Interface: Introduction
 Interface in C# is a blueprint of a class.
 It is like abstract class because all the methods which are declared inside the interface are
abstract methods.
 It cannot have method body and cannot be instantiated.
 An interface cannot contain constructors and fields.
 Interface members are by default abstract and public.
 It is used to achieve multiple inheritance which can't be achieved by class.
 It is used to achieve fully abstraction because it cannot have method body.
 Its implementation must be provided by class.
 The class which implements the interface, must provide the implementation of all the
methods declared inside the interface.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 137
Example: Interface
Example Output
1 using System;
2
3 namespace First_Prg
4 {
5
interface Calculate
6
{
7
8 int add(int a, int b);
9 }
10 class Program: Calculate
11 {
12 public int add(int a, int b)
13 {
14 return a + b;
15 }
16 static void Main(string[] args)
17 {
18 Program program = new Program();
19
int sum = program.add(10, 20);
20
Console.WriteLine("Sum is: {0}",sum);
21
22 }
23 }
24 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 138
Conditions & Looping
(Flow control and Conditional statements)
Section - 19
Flow control and Conditional statements
 Flow control and conditional statements are available in any programming language to alter
the flow of a program.
 For example, if someone wants to execute only a particular set of statements based on some
certain logic, then Flow control, and conditional statements will be useful.
 We will learn…
 If Statement
 Switch Statement
 While Loop
 For Loop
 Foreach Loop

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 140
If statement
 The if statement is used to evaluate a boolean expression, before executing a set of
statements.
 If an expression evaluates to true, then it will run one set of statements else it will run another
set of statements.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 141
Example: If..else if..else statement
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 public static void Main(string[] args)
7 {
8 int i = 20, j = 20;
9 if (i > j)
10 {
11 Console.WriteLine("i is greater than j");
12 }
13 else if (i < j)
14 {
15 Console.WriteLine("i is less than j");
16 }
17 else
18 {
19 Console.WriteLine("i is equal to j");
20 }
21 Console.ReadLine();
22 }
23 }
24 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 142
Switch Statement
 The switch statement is an enhancement to the ‘if’ statement.
 If you have multiple expressions that need to be evaluated in one shot, then writing multiple
‘if’ statements becomes an issue.
 The switch statement is used to evaluate an expression and run different statements based on
the result of the expression.
 If one condition does not evaluate to true, the switch statement will then move to the next
condition and so forth.
 If non of the condition evaluate to true, the switch statement will execute default case.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 143
Switch Statement

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 144
Example: Switch Case
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4 class Program
5 {
6 static void Main(string[] args)
7 {
8 int i = 10;
9 switch (i)
10 {
11 case 10:
12 Console.WriteLine("i is equal to 10");
13 break;
14 case 20:
15 Console.WriteLine("i is equa to 20");
16 break;
17 default:
18 Console.WriteLine("i is not equal to 10 or 20");
19 break;
20 }
21
22 Console.ReadLine();
23 }
24 }
25 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 145
While Loop
 While loop is used to evaluate a test
condition and iterate over the loop body
until the condition returns True.
 The loop ends when the condition returns
False.
 This loop is also known as a pre-tested loop
because it is commonly used when the
number of iterations is unknown to the user
ahead of time.
 Syntax:
while (testExpression)
{
// the body of the loop
}

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 146
Example: While Loop
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4
class Program
5
6
{
7 public static void Main(string[] args)
8 {
9 int i = 0, num = 5, sum = 0;
10
11 while (i <= num)
12 {
13 sum = sum + i;
14 i++;
15
}
16
17
18 Console.WriteLine("Sum is {0}",sum);
19 Console.ReadLine();
20 }
21 }
22 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 147
For Loop
 A for loop is a repetition control structure that
allows you to efficiently write a loop that needs to
execute a specific number of times.
 Syntax:
for (initialization; testExpression;
updateStatement)
{
// statements inside the body of loop
}

 Initialization - executed (one time) before the


execution of the code block.
 testExpression - defines the condition for executing
the code block.
 updateStatement - is executed (every time) after the
code block has been executed.
#2101CS511 (ASP.NET Core - I)  Unit 1 – C#
Prof. Naimish R. Vadodariya 148
Example: For Loop
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4
class Program
5
6
{
7 public static void Main(string[] args)
8 {
9 int i = 0, num = 5, sum = 0;
10
11 for (int i = 0; i < 10; i++)
12 {
13 sum += i;
14
}
15
16
Console.WriteLine("Sum is {0}",sum);
17 Console.ReadLine();
18 }
19 }
20 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 149
Foreach Loop
 The foreach loop is used to iterate over the elements of the collection. The collection may be
an array or a list.
 The Foreach loop uses the loop variable instead of the indexed element to perform the
iteration.
 It executes for each element present in the array.
 Syntax:
foreach (data_type var_name in
collection_variable)
{
// statements to be executed
}
 Limitations of foreach loop:
 They don’t keep track of the index of the item.
 They cannot iterate backwards. The loop can only go forward in one step.
 If you wish to modify the array, the foreach loop isn’t the most suitable option.

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 150
Example: Foreach Loop
Example Output
1 using System;
2 namespace MyFirstApp
3 {
4
class Program
5
6
{
7 public static void Main(string[] args)
8 {
9
10 List<int> numbers = new List<int>{ 1, 2, 3, 4, 5 };
11
12 foreach (int number in numbers)
13 {
14 Console.WriteLine(number);
15
}
16
17
18 Console.ReadLine();
19 }
20 }
21 }

#2101CS511 (ASP.NET Core - I)  Unit 1 – C#


Prof. Naimish R. Vadodariya 151
ASP.NET Core - I
#2101CS511

Thank
You

Prof. Naimish R. Vadodariya


Computer Science & Engineering
Department
Darshan University, Rajkot
Naimish.vadodariya@darshan.ac.in
8866215253

You might also like