SlideShare a Scribd company logo
C# and Dot Net Framework
Part-2
Dr. K ADISESHA
Introduction
Overview of C#
C# Program Structure
OOPS with C#
Arrays
2
Introduction to C#
Prof. K. Adisesha
Prof. K. Adisesha
Introduction
Prof. K. Adisesha
3
C# (C-Sharp) :
C# (C-Sharp) is 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.
➢ C# is used for developing:
❖ Mobile applications
❖ Desktop applications
❖ Web applications
❖ Web services
❖ Games
❖ Database applications
Introduction
Prof. K. Adisesha
4
C# IDE:
C# uses Visual Studio IDE (Integrated Development Environment) to edit and compile
code.
Introduction
Prof. K. Adisesha
5
C# IDE:
Using Visual Studio.Net IDE for compiling and executing C# programs, take the
following steps −
➢ Start Visual Studio.
➢ On the menu bar, choose File -> New -> Project.
➢ Choose Visual C# from templates, and then choose Windows.
➢ Choose Console Application.
➢ Specify a name for your project and click OK button.
➢ This creates a new project in Solution Explorer.
➢ Write code in the Code Editor.
➢ Click the Run button or press F5 key to execute the project.
Introduction
Prof. K. Adisesha
6
C# program structure:
A C# program consists of the following parts:
➢ Namespace declaration
➢ A class
➢ Class methods
➢ Class attributes
➢ A Main method
➢ Statements and Expressions
➢ Comments
C# program
Prof. K. Adisesha
7
C# program Structure:
➢ C# Comments: Comments can be used to explain C# code, and to make it more
readable. It can also be used to prevent execution when testing alternative code.
❖ Single-line comments start with two forward slashes (//).
❖ Multi-line comments start with /* and ends with */. (will not be executed).
➢ C# Identifiers: Identifiers are descriptive names in order to create understandable and
maintainable code.
➢ The general rules for naming Identifiers/variables are:
❖ Names can contain letters, digits and the underscore character (_)
❖ Names must begin with a letter
❖ Names should start with a lowercase letter and it cannot contain whitespace
❖ Names are case sensitive ("myVar" and "myvar" are different variables)
❖ Reserved words (like C# keywords, such as int or double) cannot be used as names
C# program
Prof. K. Adisesha
8
C# program Structure:
➢ C# Variables: Variables are containers for storing data values. All C# variables must
be identified with unique names.
❖ Syntax: type variableName = value;
❖ Example: string name = “K. Adisesha";
int x = 5, y = 6, z = 50;
➢ C# Constants: The const keyword is useful when you want a variable to always store
the same value. Example: const int Num = 15;
Num = 20; // error
➢ Display Variables: The WriteLine() method is often used to display variable values to
the console window. To combine both text and a variable, use the + character:
Example: string name = "John";
Console.WriteLine("Hello " + name);
Data Type Size Description
Int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -/+9,223,372,036,854,775,808
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
bool 1 bytes Stores true or false values
char 2 bytes Stores a single character/letter, surrounded by single quotes
string 2 bytes per character Stores a sequence of characters, surrounded by double quotes
C# program
Prof. K. Adisesha
9
C# program Structure:
C# Data Types: A data type specifies the size and type of variable values. It is important
to use the correct data type for the corresponding variable to save time and memory.
➢ The most common data types are:
C# Programming
Prof. K. Adisesha
10
C# program Structure:
C# Type Casting: Type casting is when you assign a value of one data type to another type.
➢ In C#, there are two types of casting:
➢ Implicit Casting (automatically) - converting a smaller type to a larger type size
❖ char -> int -> long -> float -> double
❖ Example: int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
➢ Explicit Casting (manually) - converting a larger type to a smaller size type
➢ It must be done manually by placing the type in parentheses in front of the value:
❖ double -> float -> long -> int -> char
❖ Example: double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
C# Programming
Prof. K. Adisesha
11
C# program Structure:
Type Conversion Methods: It is also possible to convert data types explicitly by using built-
in methods,
➢ In C#, there are various built-in methods for types conversion:
❖ Convert.ToBoolean Example:
❖ Convert.ToDouble
❖ Convert.ToString
❖ Convert.ToInt32 (int)
❖ Convert.ToInt64 (long)
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to string
C# Programming
Prof. K. Adisesha
12
C# program Structure:
C# User Input/output: The user can input or display output his or hers data, which is
stored in the variable using built-in methods.
User Input:The Console.ReadLine() method returns a string.
❖ // Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();
User Output:Console.WriteLine() is used to output (print) values..
❖ // Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);
❖ Example: Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
C# Programming
Prof. K. Adisesha
13
C# program Structure:
C# - Operators: An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
➢ C# has rich set of built-in operators and provides the following type of operators.
❖ Arithmetic Operators
❖ Relational Operators
❖ Logical Operators
❖ Bitwise Operators
❖ Assignment Operators
❖ Misc Operators
C# Programming
Prof. K. Adisesha
14
C# - Operators:
Arithmetic Operators: Following table shows all the arithmetic operators supported by C#.
➢ Assume variable A holds 10 and variable B holds 20 then −.
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
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes
true.
(A == B) is false
!= Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(A != B) is true.
> Checks if the value of left operand is greater than the value of right operand (A > B) is false
< Checks if the value of left operand is less than the value of right operand (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand (A >= B) is false
<= Checks if the value of left operand is less than or equal to the value of right operand, (A <= B) is true.
C# Programming
Prof. K. Adisesha
15
C# - Operators:
Relational Operators: Following table shows all the relational operators supported by C#.
➢ Assume variable A holds 10 and variable B holds 20 then −.
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes
true.
(A == B) is false
!= Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(A != B) is true.
> Checks if the value of left operand is greater than the value of right operand (A > B) is false
< Checks if the value of left operand is less than the value of right operand (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand (A >= B) is false
<= Checks if the value of left operand is less than or equal to the value of right operand, (A <= B) is true.
C# Programming
Prof. K. Adisesha
16
C# - Operators:
Relational Operators: Following table shows all the relational operators supported by C#.
➢ Assume variable A holds 10 and variable B holds 20 then −.
C# Programming
Prof. K. Adisesha
17
C# - Operators:
Logical Operators: Following table shows all the logical operators supported by C#.
➢ Assume variable A holds Boolean value true and variable B holds value false, then:
Operator Description Example
&& Called Logical AND operator. If both the operands are non zero then condition
becomes true.
(A && B) is false.
|| Called Logical OR Operator. If any of the two operands is non zero then condition
becomes true.
(A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a
condition is true then Logical NOT operator will make false.
!(A && B) is true.
Bitwise Operators: Bitwise operator works on bits and perform bit by bit operation.
➢ The Bitwise operator supported by C# are: “ &, |, ~ , ^ , >> , << ”
C# Programming
Prof. K. Adisesha
18
C# - Operators:
Miscellaneous Operators: There are few other important operators including sizeof, typeof
and ? : supported by C#.
Operator Description Example
sizeof() Returns the size of a data type. sizeof(int), returns 4.
typeof() Returns the type of a class. typeof(StreamReader);
& Returns the address of an variable. &a; returns actual address of the variable.
* Pointer to a variable. *a; creates pointer named 'a' to a variable.
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y
is Determines whether an object is of a
certain type.
If( Ford is Car) // checks if Ford is an object of the Car
class.
as Cast without raising an exception if the
cast fails.
Object obj = new StringReader("Hello");StringReader r
= obj as StringReader;
C# Programming
Prof. K. Adisesha
19
C# - Control Structures:
Conditional statements: There are few conditions statements to perform different actions
for different decisions that are supported by C#.
➢ C# has the following conditional statements:
❖ if :Use if to specify a block of code to be executed, if a specified condition is true
❖ else : Use else to specify a block of code to be executed, if the same condition is false
❖ else if :Use else if to specify a new condition to test, if the first condition is false
❖ Switch : Use switch to specify many alternative blocks of code to be executed
Example
if (30 > 18)
{
Console.WriteLine(“30 is greater than 18");
}
C# Programming
Prof. K. Adisesha
20
C# - Control Structures:
Short Hand If...Else (Ternary Operator): short-hand if else, which is known as the ternary
operator because it consists of three operands.
➢ It can be used to replace multiple lines of code with a single line.
➢ It is often used to replace simple if else statements:
Syntax: variable = (condition) ? expressionTrue : expressionFalse;
Example
int Percentage = 60;
if (time < 35)
{ Console.WriteLine(“First class"); }
else
{ Console.WriteLine(“Fail."); }
int Percentage = 60;
string result = (Percentage < 35) ? “First Class." : “Fail";
Console.WriteLine(result);
Example :Ternary Operator
C# Programming
Prof. K. Adisesha
21
C# - Control Structures:
Switch Statements : Use the switch statement to select one of many code blocks to be
executed.
➢ The switch expression is evaluated once
➢ The value of the expression is compared with the values of each case
➢ If there is a match, the associated block of code is executed:
Example
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break; }
C# Programming
Prof. K. Adisesha
22
C# - Control Structures:
C# - Loops: Loops can execute a block of code as long as a specified condition is reached.
➢ C# provides following types of loop to handle looping requirements.
Loop Type Description
while loop It repeats a statement or a group of statements while a given condition is true.
It tests the condition before executing the loop body.
for loop It executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
do...while loop It is similar to a while statement, except that it tests the condition at the end of the
loop body
nested loops You can use one or more loop inside any another while, for or do..while loop.
C# Programming
Prof. K. Adisesha
23
C# - Loops:
➢ C# For Loop: When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop.
❖ Syntax : for (statement 1; statement 2; statement 3)
{ // code block to be executed }
➢ foreach Loop: There is also a foreach loop, which is used exclusively to loop through
elements in an array:
❖ Syntax : foreach (type variableName in arrayName)
{
// code block to be executed
}
Example
for (int i = 0; i < 5; i++)
{ Console.WriteLine(i);
}
Example
string[] Course = {"BCA", "BCom",
"BBA", "BHM"};
foreach (string i in Course)
{ Console.WriteLine(i);
}
C# Programming
Prof. K. Adisesha
24
C# - Arrays:
An array stores a fixed-size sequential collection of elements of the same type.
➢ To declare an array in C#, you can use the following syntax −
❖ Syntax : datatype[] arrayName;
➢ Array is a reference type, so you need to use the new keyword to create an instance of the
array.
❖ Example : double[] balance = new double[10];
➢ You can also create and initialize an array, as shown −
❖ Example : int [] marks = new int[5] { 99, 98, 92, 97, 95};
➢ You can copy an array variable into another target array variable. In such case, both the
target and source point to the same memory location −
❖ Example: int [] marks = new int[] { 99, 98, 92, 97, 95};
int[] score = marks;
C# Programming
Prof. K. Adisesha
25
Multidimensional Arrays:
A multidimensional array is basically an array of arrays which can have any number of
dimensions. The most common are two-dimensional arrays (2D).
➢ The single comma [,] specifies that the array is two-dimensional. A three-dimensional
array would have two commas: int[,,].
➢ To create a 2D array, add each array within its own set of curly braces, and insert a
comma (,) inside the square brackets.
❖ Syntax : int[,] numbers = { {1, 2, 3}, {10, 20, 30} };
➢ To access an element of a two-dimensional array, you must specify two indexes.
❖ Example : int[,] numbers = { {1, 2, 3}, {10, 20, 30} };
Console.WriteLine(numbers[0, 2]); // Outputs 3
C# Programming
Prof. K. Adisesha
26
C# Methods / Functions:
A method is a block of code which only runs when it is called.You can pass data, known as
parameters, into a method.
➢ Methods are used to perform certain actions, and they are also known as functions.
➢ A method is defined with the name of the method, followed by parentheses ().
➢ C# provides some pre-defined methods, such as Main().
❖ Create a method inside the Program class:
class Program
{ static void MyMethod()
{ // code to be executed }
}
static void MyMethod()
{ Console.WriteLine(“Hello Sunny!");
}
static void Main(string[] args)
{ MyMethod();
}
Outputs : Hello Sunny!
C# Programming
Prof. K. Adisesha
27
C# Methods / Functions:
Parameters and Arguments: Information can be passed to methods as parameter.
Parameters act as variables inside the method.
➢ They are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
➢ Example:
static void MyMethod(string fname, int age)
{ Console.WriteLine(fname + " is " + age);
}
static void Main(string[] args)
{ MyMethod(“Adi”, 48);
MyMethod(“Prajwal", 18);
MyMethod(“Sunny", 16); }
Outputs : Adi is 48
Prajwal is 18
Sunny is 16
C# Programming
Prof. K. Adisesha
28
C# OOP:
OOP stands for Object-Oriented Programming, which is about creating objects that
contain both data and methods.
➢ Object-oriented programming has several advantages over procedural programming:
❖ OOP is faster and easier to execute
❖ OOP provides a clear structure for the programs
❖ OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
❖ OOP makes it possible to create full reusable applications with less code and shorter
development time
C# Programming
Prof. K. Adisesha
29
C# Object and Class:
C# is an object-oriented language, program is designed using objects and classes in C#.
➢ C# Object: Object is a runtime entity, it is created at runtime. Object is an entity that has
state and behavior. Here, state means data and behavior means functionality.
❖ Example: Student s1 = new Student();//creating an object of Student
➢ C# Class : In C#, class is a group of similar objects. It is a template from which objects
are created. It can have fields, methods, constructors etc.
❖ Let's see an example of C# class that has two fields only.
public class Student
{ int id;//field or data member
String name;//field or data member
}
C# Programming
Prof. K. Adisesha
30
C# - Inheritance:
Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application.
➢ This also provides an opportunity to reuse the code functionality and speeds up
implementation time.
➢ Base and Derived Classes: A class can be derived from more than one class or interface,
which means that it can inherit data and functions from multiple base classes or
interfaces.
❖ Example: <acess-specifier> class <base_class> //Base class
{ ... }
class <derived_class> : <base_class> //Derived class
{ ... }
C# Programming
Prof. K. Adisesha
31
C# - Polymorphism:
In object-oriented programming paradigm, polymorphism is often expressed as 'one
interface, multiple functions'.
➢ Polymorphism can be static or dynamic.
❖ In static polymorphism, the response to a function is determined at the compile time.
❖ In dynamic polymorphism, it is decided at run-time..
➢ Static Polymorphism: The mechanism of linking a function with an object during compile
time is called early binding. It is also called static binding.
➢ C# provides two techniques to implement static polymorphism:
❖ Function overloading
❖ Operator overloading
C# Programming
Prof. K. Adisesha
32
C# - Polymorphism:
Function overloading: Also called Method overloading, having two or more methods with
same name but different in parameters, is known as method overloading in C#.
➢ You can perform method overloading in C# by two ways:
❖ By changing number of arguments
❖ By changing data type of the arguments.
➢ Example: public class TestMemberOverloading
{ public static void Main( )
{
Console.WriteLine(Cal.add(15, 20));
Console.WriteLine(Cal.add(15, 20, 25));
}
}
using System;
public class Cal
{
public static int add(int a, int b)
{ return a + b; }
public static int add(int a, int b, int c)
{ return a + b + c; }
}
C# Programming
Prof. K. Adisesha
33
C# - Polymorphism:
C# - Operator Overloading: You can redefine or overload most of the built-in operators
available in C#. Thus a programmer can use operators with user-defined types as well.
➢ Overloaded operators are functions with special names the keyword operator followed by
the symbol for the operator being defined. similar to any other function, an overloaded
operator has a return type and a parameter list.
➢ Example, public static Box operator+ (Box b, Box c)
{ Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}
❖ function implements the addition operator (+)
for a user-defined class Box. It adds the
attributes of two Box objects and returns the
resultant Box object.
C# Programming
Prof. K. Adisesha
34
C# - Interfaces:
An interface is defined as a syntactical contract that all the classes inheriting the interface
should follow. The interface defines the 'what' part of the syntactical contract and the
deriving classes define the 'how' part of the syntactical contract.
➢ Interfaces define properties, methods, and events, which are the members of the interface.
Interfaces contain only the declaration of the members.
➢ Interfaces are declared using the interface keyword. It is similar to class declaration.
Interface statements are public by default.
➢ Syntax: public interface ITransactions
{ // interface members
void showTransaction();
double getAmount();
}
Example: // Interface
interface Student
{void StudentCourse( ); // interface method (does not have a body) }
class BCA : Student
{ public void StudentCourse( )
{ // The body of StudentCourse( ) is provided here
Console.WriteLine(“BCA Students Study C#"); } }
C# Programming
Prof. K. Adisesha
35
C# - Interfaces:
An interface is defined as a syntactical contract that all the classes inheriting the interface
should follow. The interface defines the 'what' part of the syntactical contract and the
deriving classes define the 'how' part of the syntactical contract.
➢ Like abstract classes, interfaces cannot be used to create objects
➢ Interface methods do not have a body - the body is provided by the "implement" class
➢ On implementation of an interface, you must override all of its methods
➢ Interfaces can contain properties and methods, but not fields/variables
➢ Interface members are by default abstract and public
➢ An interface cannot contain a constructor (as it cannot be used to create objects)
C# Programming
Prof. K. Adisesha
36
C# Enumerations:
An enum is a special "class" that represents a group of constants (unchangeable/read-
only variables).
➢ Enum is short for "enumerations", which means "specifically listed".
➢ To create an enum, use the enum keyword (instead of class or interface), and separate the
enum items with a comma.
➢ By default, the first item of an enum has the value 0. The second has the value 1, and so
on.
➢ Example:
class Program
{
enum Level
{ Low,
Medium,
High
}
//You can access enum items with the dot syntax:
static void Main(string[] args)
{ Level myVar = Level.Medium;
Console.WriteLine(myVar);
}
}
C# Programming
Prof. K. Adisesha
37
C# - Exception Handling:
An exception is a problem that arises during the execution of a program.
A C# exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
➢ Exceptions provide a way to transfer control from one part of a program to another.
➢ C# exception handling is built upon four keywords:
❖ try
❖ catch
❖ finally
❖ throw
try { // statements causing exception }
catch( ExceptionName e1 ) { // error handling code }
catch( ExceptionName e2 ) { // error handling code }
catch( ExceptionName eN ) { // error handling code }
finally { // statements to be executed }
C# Programming
Prof. K. Adisesha
38
C# - Exception Handling:
A C# exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
➢ try − A try block identifies a block of code for which particular exceptions is activated. It is
followed by one or more catch blocks.
➢ catch − A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an exception.
➢ finally − The finally block is used to execute a given set of statements, whether an exception is
thrown or not thrown. For example, if you open a file, it must be closed whether an exception is
raised or not.
➢ throw − A program throws an exception when a problem shows up. This is done using a throw
keyword.
C# Programming
Prof. K. Adisesha
39
C# - File I/O:
A file is a collection of data stored in a disk with a specific name and a directory path.
When a file is opened for reading or writing, it becomes a stream.
➢ The stream is basically the sequence of bytes passing through the communication path.
➢ There are two main streams: the input stream and the output stream.
❖ The input stream is used for reading data from file (read operation).
❖ The output stream is used for writing into the file (write operation).
➢ The File class from the System.IO namespace, allows us to work with files.
➢ Example:
using System.IO; // include the System.IO namespace
File.SomeFileMethod(); // use the file class with methods
Discussion
Prof. K. Adisesha
40
Queries ?
Prof. K. Adisesha
9449081542

More Related Content

ODP
Introduction of Html/css/js
PPT
Java applets
PPTX
C# lecture 2: Literals , Variables and Data Types in C#
PDF
Java variable types
PDF
tree traversals.pdf
PPTX
Introduction to c programming language
PPTX
C# programming language
PPT
Variables in C Programming
Introduction of Html/css/js
Java applets
C# lecture 2: Literals , Variables and Data Types in C#
Java variable types
tree traversals.pdf
Introduction to c programming language
C# programming language
Variables in C Programming

What's hot (20)

PPTX
C++ presentation
PPS
Interface
PPTX
Basics of JAVA programming
PPTX
Data types in java
PPTX
Object oriented programming in java
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
ODP
Patterns in Python
 
PPTX
Cascading Style Sheet (CSS)
PDF
Learn C# Programming - Data Types & Type Conversion
PPTX
User Interface Analysis and Design
PPT
Javascript
PPTX
css.ppt
PPTX
Ado.Net Tutorial
PPT
JDBC – Java Database Connectivity
PPT
DOC
Jumping statements
PDF
C# Dot net unit-3.pdf
PPSX
Javascript variables and datatypes
PPTX
Java Introduction
C++ presentation
Interface
Basics of JAVA programming
Data types in java
Object oriented programming in java
PHP - DataType,Variable,Constant,Operators,Array,Include and require
Patterns in Python
 
Cascading Style Sheet (CSS)
Learn C# Programming - Data Types & Type Conversion
User Interface Analysis and Design
Javascript
css.ppt
Ado.Net Tutorial
JDBC – Java Database Connectivity
Jumping statements
C# Dot net unit-3.pdf
Javascript variables and datatypes
Java Introduction
Ad

Similar to C# Dot net unit-2.pdf (20)

PPTX
PPSX
DISE - Windows Based Application Development in C#
PPTX
2.overview of c#
PPSX
DITEC - Programming with C#.NET
PPTX
unit 1 (1).pptx
PPT
Introduction to C#
PPTX
C# 101: Intro to Programming with C#
PPTX
CS4443 - Modern Programming Language - I Lecture (2)
PPTX
PPT
Lecture 2
PPTX
Introduction to C#.pptx for all BSIT students
PPTX
C sharp part 001
PDF
C Sharp: Basic to Intermediate Part 01
PPTX
CSharp Language Overview Part 1
PPT
Visula C# Programming Lecture 2
PPTX
Chapter3: fundamental programming
PPTX
Chapter 2 c#
PPT
Presentatiooooooooooon00000000000001.ppt
PPT
ch4 is the one of biggest tool in AI.ppt
DISE - Windows Based Application Development in C#
2.overview of c#
DITEC - Programming with C#.NET
unit 1 (1).pptx
Introduction to C#
C# 101: Intro to Programming with C#
CS4443 - Modern Programming Language - I Lecture (2)
Lecture 2
Introduction to C#.pptx for all BSIT students
C sharp part 001
C Sharp: Basic to Intermediate Part 01
CSharp Language Overview Part 1
Visula C# Programming Lecture 2
Chapter3: fundamental programming
Chapter 2 c#
Presentatiooooooooooon00000000000001.ppt
ch4 is the one of biggest tool in AI.ppt
Ad

More from Prof. Dr. K. Adisesha (20)

PDF
MACHINE LEARNING Notes by Dr. K. Adisesha
PDF
Probabilistic and Stochastic Models Unit-3-Adi.pdf
PDF
Genetic Algorithm in Machine Learning PPT by-Adi
PDF
Unsupervised Machine Learning PPT Adi.pdf
PDF
Supervised Machine Learning PPT by K. Adisesha
PDF
Introduction to Machine Learning PPT by K. Adisesha
PPSX
Design and Analysis of Algorithms ppt by K. Adi
PPSX
Data Structure using C by Dr. K Adisesha .ppsx
PDF
Operating System-4 "File Management" by Adi.pdf
PDF
Operating System-3 "Memory Management" by Adi.pdf
PDF
Operating System Concepts Part-1 by_Adi.pdf
PDF
Operating System-2_Process Managementby_Adi.pdf
PDF
Software Engineering notes by K. Adisesha.pdf
PDF
Software Engineering-Unit 1 by Adisesha.pdf
PDF
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
PDF
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
PDF
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
PDF
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
PDF
Computer Networks Notes by -Dr. K. Adisesha
PDF
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
MACHINE LEARNING Notes by Dr. K. Adisesha
Probabilistic and Stochastic Models Unit-3-Adi.pdf
Genetic Algorithm in Machine Learning PPT by-Adi
Unsupervised Machine Learning PPT Adi.pdf
Supervised Machine Learning PPT by K. Adisesha
Introduction to Machine Learning PPT by K. Adisesha
Design and Analysis of Algorithms ppt by K. Adi
Data Structure using C by Dr. K Adisesha .ppsx
Operating System-4 "File Management" by Adi.pdf
Operating System-3 "Memory Management" by Adi.pdf
Operating System Concepts Part-1 by_Adi.pdf
Operating System-2_Process Managementby_Adi.pdf
Software Engineering notes by K. Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Computer Networks Notes by -Dr. K. Adisesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha

Recently uploaded (20)

PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
RMMM.pdf make it easy to upload and study
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Cell Structure & Organelles in detailed.
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Cell Types and Its function , kingdom of life
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
Anesthesia in Laparoscopic Surgery in India
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
RMMM.pdf make it easy to upload and study
Supply Chain Operations Speaking Notes -ICLT Program
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Weekly quiz Compilation Jan -July 25.pdf
human mycosis Human fungal infections are called human mycosis..pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Cell Structure & Organelles in detailed.
Computing-Curriculum for Schools in Ghana
Cell Types and Its function , kingdom of life
Microbial disease of the cardiovascular and lymphatic systems
Final Presentation General Medicine 03-08-2024.pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
O5-L3 Freight Transport Ops (International) V1.pdf
Orientation - ARALprogram of Deped to the Parents.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025

C# Dot net unit-2.pdf

  • 1. C# and Dot Net Framework Part-2 Dr. K ADISESHA
  • 2. Introduction Overview of C# C# Program Structure OOPS with C# Arrays 2 Introduction to C# Prof. K. Adisesha Prof. K. Adisesha
  • 3. Introduction Prof. K. Adisesha 3 C# (C-Sharp) : C# (C-Sharp) is 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. ➢ C# is used for developing: ❖ Mobile applications ❖ Desktop applications ❖ Web applications ❖ Web services ❖ Games ❖ Database applications
  • 4. Introduction Prof. K. Adisesha 4 C# IDE: C# uses Visual Studio IDE (Integrated Development Environment) to edit and compile code.
  • 5. Introduction Prof. K. Adisesha 5 C# IDE: Using Visual Studio.Net IDE for compiling and executing C# programs, take the following steps − ➢ Start Visual Studio. ➢ On the menu bar, choose File -> New -> Project. ➢ Choose Visual C# from templates, and then choose Windows. ➢ Choose Console Application. ➢ Specify a name for your project and click OK button. ➢ This creates a new project in Solution Explorer. ➢ Write code in the Code Editor. ➢ Click the Run button or press F5 key to execute the project.
  • 6. Introduction Prof. K. Adisesha 6 C# program structure: A C# program consists of the following parts: ➢ Namespace declaration ➢ A class ➢ Class methods ➢ Class attributes ➢ A Main method ➢ Statements and Expressions ➢ Comments
  • 7. C# program Prof. K. Adisesha 7 C# program Structure: ➢ C# Comments: Comments can be used to explain C# code, and to make it more readable. It can also be used to prevent execution when testing alternative code. ❖ Single-line comments start with two forward slashes (//). ❖ Multi-line comments start with /* and ends with */. (will not be executed). ➢ C# Identifiers: Identifiers are descriptive names in order to create understandable and maintainable code. ➢ The general rules for naming Identifiers/variables are: ❖ Names can contain letters, digits and the underscore character (_) ❖ Names must begin with a letter ❖ Names should start with a lowercase letter and it cannot contain whitespace ❖ Names are case sensitive ("myVar" and "myvar" are different variables) ❖ Reserved words (like C# keywords, such as int or double) cannot be used as names
  • 8. C# program Prof. K. Adisesha 8 C# program Structure: ➢ C# Variables: Variables are containers for storing data values. All C# variables must be identified with unique names. ❖ Syntax: type variableName = value; ❖ Example: string name = “K. Adisesha"; int x = 5, y = 6, z = 50; ➢ C# Constants: The const keyword is useful when you want a variable to always store the same value. Example: const int Num = 15; Num = 20; // error ➢ Display Variables: The WriteLine() method is often used to display variable values to the console window. To combine both text and a variable, use the + character: Example: string name = "John"; Console.WriteLine("Hello " + name);
  • 9. Data Type Size Description Int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647 long 8 bytes Stores whole numbers from -/+9,223,372,036,854,775,808 float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits bool 1 bytes Stores true or false values char 2 bytes Stores a single character/letter, surrounded by single quotes string 2 bytes per character Stores a sequence of characters, surrounded by double quotes C# program Prof. K. Adisesha 9 C# program Structure: C# Data Types: A data type specifies the size and type of variable values. It is important to use the correct data type for the corresponding variable to save time and memory. ➢ The most common data types are:
  • 10. C# Programming Prof. K. Adisesha 10 C# program Structure: C# Type Casting: Type casting is when you assign a value of one data type to another type. ➢ In C#, there are two types of casting: ➢ Implicit Casting (automatically) - converting a smaller type to a larger type size ❖ char -> int -> long -> float -> double ❖ Example: int myInt = 9; double myDouble = myInt; // Automatic casting: int to double ➢ Explicit Casting (manually) - converting a larger type to a smaller size type ➢ It must be done manually by placing the type in parentheses in front of the value: ❖ double -> float -> long -> int -> char ❖ Example: double myDouble = 9.78; int myInt = (int) myDouble; // Manual casting: double to int
  • 11. C# Programming Prof. K. Adisesha 11 C# program Structure: Type Conversion Methods: It is also possible to convert data types explicitly by using built- in methods, ➢ In C#, there are various built-in methods for types conversion: ❖ Convert.ToBoolean Example: ❖ Convert.ToDouble ❖ Convert.ToString ❖ Convert.ToInt32 (int) ❖ Convert.ToInt64 (long) int myInt = 10; double myDouble = 5.25; bool myBool = true; Console.WriteLine(Convert.ToString(myInt)); // convert int to string Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int Console.WriteLine(Convert.ToString(myBool)); // convert bool to string
  • 12. C# Programming Prof. K. Adisesha 12 C# program Structure: C# User Input/output: The user can input or display output his or hers data, which is stored in the variable using built-in methods. User Input:The Console.ReadLine() method returns a string. ❖ // Create a string variable and get user input from the keyboard and store it in the variable string userName = Console.ReadLine(); User Output:Console.WriteLine() is used to output (print) values.. ❖ // Print the value of the variable (userName), which will display the input value Console.WriteLine("Username is: " + userName); ❖ Example: Console.WriteLine("Enter your age:"); int age = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Your age is: " + age);
  • 13. C# Programming Prof. K. Adisesha 13 C# program Structure: C# - Operators: An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. ➢ C# has rich set of built-in operators and provides the following type of operators. ❖ Arithmetic Operators ❖ Relational Operators ❖ Logical Operators ❖ Bitwise Operators ❖ Assignment Operators ❖ Misc Operators
  • 14. C# Programming Prof. K. Adisesha 14 C# - Operators: Arithmetic Operators: Following table shows all the arithmetic operators supported by C#. ➢ Assume variable A holds 10 and variable B holds 20 then −. 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
  • 15. Operator Description Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is false != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand (A > B) is false < Checks if the value of left operand is less than the value of right operand (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand (A >= B) is false <= Checks if the value of left operand is less than or equal to the value of right operand, (A <= B) is true. C# Programming Prof. K. Adisesha 15 C# - Operators: Relational Operators: Following table shows all the relational operators supported by C#. ➢ Assume variable A holds 10 and variable B holds 20 then −.
  • 16. Operator Description Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is false != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand (A > B) is false < Checks if the value of left operand is less than the value of right operand (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand (A >= B) is false <= Checks if the value of left operand is less than or equal to the value of right operand, (A <= B) is true. C# Programming Prof. K. Adisesha 16 C# - Operators: Relational Operators: Following table shows all the relational operators supported by C#. ➢ Assume variable A holds 10 and variable B holds 20 then −.
  • 17. C# Programming Prof. K. Adisesha 17 C# - Operators: Logical Operators: Following table shows all the logical operators supported by C#. ➢ Assume variable A holds Boolean value true and variable B holds value false, then: Operator Description Example && Called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. (A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true. Bitwise Operators: Bitwise operator works on bits and perform bit by bit operation. ➢ The Bitwise operator supported by C# are: “ &, |, ~ , ^ , >> , << ”
  • 18. C# Programming Prof. K. Adisesha 18 C# - Operators: Miscellaneous Operators: There are few other important operators including sizeof, typeof and ? : supported by C#. Operator Description Example sizeof() Returns the size of a data type. sizeof(int), returns 4. typeof() Returns the type of a class. typeof(StreamReader); & Returns the address of an variable. &a; returns actual address of the variable. * Pointer to a variable. *a; creates pointer named 'a' to a variable. ? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y is Determines whether an object is of a certain type. If( Ford is Car) // checks if Ford is an object of the Car class. as Cast without raising an exception if the cast fails. Object obj = new StringReader("Hello");StringReader r = obj as StringReader;
  • 19. C# Programming Prof. K. Adisesha 19 C# - Control Structures: Conditional statements: There are few conditions statements to perform different actions for different decisions that are supported by C#. ➢ C# has the following conditional statements: ❖ if :Use if to specify a block of code to be executed, if a specified condition is true ❖ else : Use else to specify a block of code to be executed, if the same condition is false ❖ else if :Use else if to specify a new condition to test, if the first condition is false ❖ Switch : Use switch to specify many alternative blocks of code to be executed Example if (30 > 18) { Console.WriteLine(“30 is greater than 18"); }
  • 20. C# Programming Prof. K. Adisesha 20 C# - Control Structures: Short Hand If...Else (Ternary Operator): short-hand if else, which is known as the ternary operator because it consists of three operands. ➢ It can be used to replace multiple lines of code with a single line. ➢ It is often used to replace simple if else statements: Syntax: variable = (condition) ? expressionTrue : expressionFalse; Example int Percentage = 60; if (time < 35) { Console.WriteLine(“First class"); } else { Console.WriteLine(“Fail."); } int Percentage = 60; string result = (Percentage < 35) ? “First Class." : “Fail"; Console.WriteLine(result); Example :Ternary Operator
  • 21. C# Programming Prof. K. Adisesha 21 C# - Control Structures: Switch Statements : Use the switch statement to select one of many code blocks to be executed. ➢ The switch expression is evaluated once ➢ The value of the expression is compared with the values of each case ➢ If there is a match, the associated block of code is executed: Example switch(expression) { case x: // code block break; case y: // code block break; default: // code block break; }
  • 22. C# Programming Prof. K. Adisesha 22 C# - Control Structures: C# - Loops: Loops can execute a block of code as long as a specified condition is reached. ➢ C# provides following types of loop to handle looping requirements. Loop Type Description while loop It repeats a statement or a group of statements while a given condition is true. It tests the condition before executing the loop body. for loop It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. do...while loop It is similar to a while statement, except that it tests the condition at the end of the loop body nested loops You can use one or more loop inside any another while, for or do..while loop.
  • 23. C# Programming Prof. K. Adisesha 23 C# - Loops: ➢ C# For Loop: When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. ❖ Syntax : for (statement 1; statement 2; statement 3) { // code block to be executed } ➢ foreach Loop: There is also a foreach loop, which is used exclusively to loop through elements in an array: ❖ Syntax : foreach (type variableName in arrayName) { // code block to be executed } Example for (int i = 0; i < 5; i++) { Console.WriteLine(i); } Example string[] Course = {"BCA", "BCom", "BBA", "BHM"}; foreach (string i in Course) { Console.WriteLine(i); }
  • 24. C# Programming Prof. K. Adisesha 24 C# - Arrays: An array stores a fixed-size sequential collection of elements of the same type. ➢ To declare an array in C#, you can use the following syntax − ❖ Syntax : datatype[] arrayName; ➢ Array is a reference type, so you need to use the new keyword to create an instance of the array. ❖ Example : double[] balance = new double[10]; ➢ You can also create and initialize an array, as shown − ❖ Example : int [] marks = new int[5] { 99, 98, 92, 97, 95}; ➢ You can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location − ❖ Example: int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks;
  • 25. C# Programming Prof. K. Adisesha 25 Multidimensional Arrays: A multidimensional array is basically an array of arrays which can have any number of dimensions. The most common are two-dimensional arrays (2D). ➢ The single comma [,] specifies that the array is two-dimensional. A three-dimensional array would have two commas: int[,,]. ➢ To create a 2D array, add each array within its own set of curly braces, and insert a comma (,) inside the square brackets. ❖ Syntax : int[,] numbers = { {1, 2, 3}, {10, 20, 30} }; ➢ To access an element of a two-dimensional array, you must specify two indexes. ❖ Example : int[,] numbers = { {1, 2, 3}, {10, 20, 30} }; Console.WriteLine(numbers[0, 2]); // Outputs 3
  • 26. C# Programming Prof. K. Adisesha 26 C# Methods / Functions: A method is a block of code which only runs when it is called.You can pass data, known as parameters, into a method. ➢ Methods are used to perform certain actions, and they are also known as functions. ➢ A method is defined with the name of the method, followed by parentheses (). ➢ C# provides some pre-defined methods, such as Main(). ❖ Create a method inside the Program class: class Program { static void MyMethod() { // code to be executed } } static void MyMethod() { Console.WriteLine(“Hello Sunny!"); } static void Main(string[] args) { MyMethod(); } Outputs : Hello Sunny!
  • 27. C# Programming Prof. K. Adisesha 27 C# Methods / Functions: Parameters and Arguments: Information can be passed to methods as parameter. Parameters act as variables inside the method. ➢ They are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. ➢ Example: static void MyMethod(string fname, int age) { Console.WriteLine(fname + " is " + age); } static void Main(string[] args) { MyMethod(“Adi”, 48); MyMethod(“Prajwal", 18); MyMethod(“Sunny", 16); } Outputs : Adi is 48 Prajwal is 18 Sunny is 16
  • 28. C# Programming Prof. K. Adisesha 28 C# OOP: OOP stands for Object-Oriented Programming, which is about creating objects that contain both data and methods. ➢ Object-oriented programming has several advantages over procedural programming: ❖ OOP is faster and easier to execute ❖ OOP provides a clear structure for the programs ❖ OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug ❖ OOP makes it possible to create full reusable applications with less code and shorter development time
  • 29. C# Programming Prof. K. Adisesha 29 C# Object and Class: C# is an object-oriented language, program is designed using objects and classes in C#. ➢ C# Object: Object is a runtime entity, it is created at runtime. Object is an entity that has state and behavior. Here, state means data and behavior means functionality. ❖ Example: Student s1 = new Student();//creating an object of Student ➢ C# Class : In C#, class is a group of similar objects. It is a template from which objects are created. It can have fields, methods, constructors etc. ❖ Let's see an example of C# class that has two fields only. public class Student { int id;//field or data member String name;//field or data member }
  • 30. C# Programming Prof. K. Adisesha 30 C# - Inheritance: Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. ➢ This also provides an opportunity to reuse the code functionality and speeds up implementation time. ➢ Base and Derived Classes: A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces. ❖ Example: <acess-specifier> class <base_class> //Base class { ... } class <derived_class> : <base_class> //Derived class { ... }
  • 31. C# Programming Prof. K. Adisesha 31 C# - Polymorphism: In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'. ➢ Polymorphism can be static or dynamic. ❖ In static polymorphism, the response to a function is determined at the compile time. ❖ In dynamic polymorphism, it is decided at run-time.. ➢ Static Polymorphism: The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. ➢ C# provides two techniques to implement static polymorphism: ❖ Function overloading ❖ Operator overloading
  • 32. C# Programming Prof. K. Adisesha 32 C# - Polymorphism: Function overloading: Also called Method overloading, having two or more methods with same name but different in parameters, is known as method overloading in C#. ➢ You can perform method overloading in C# by two ways: ❖ By changing number of arguments ❖ By changing data type of the arguments. ➢ Example: public class TestMemberOverloading { public static void Main( ) { Console.WriteLine(Cal.add(15, 20)); Console.WriteLine(Cal.add(15, 20, 25)); } } using System; public class Cal { public static int add(int a, int b) { return a + b; } public static int add(int a, int b, int c) { return a + b + c; } }
  • 33. C# Programming Prof. K. Adisesha 33 C# - Polymorphism: C# - Operator Overloading: You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. ➢ Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. similar to any other function, an overloaded operator has a return type and a parameter list. ➢ Example, public static Box operator+ (Box b, Box c) { Box box = new Box(); box.length = b.length + c.length; box.breadth = b.breadth + c.breadth; box.height = b.height + c.height; return box; } ❖ function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object.
  • 34. C# Programming Prof. K. Adisesha 34 C# - Interfaces: An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract. ➢ Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. ➢ Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. ➢ Syntax: public interface ITransactions { // interface members void showTransaction(); double getAmount(); } Example: // Interface interface Student {void StudentCourse( ); // interface method (does not have a body) } class BCA : Student { public void StudentCourse( ) { // The body of StudentCourse( ) is provided here Console.WriteLine(“BCA Students Study C#"); } }
  • 35. C# Programming Prof. K. Adisesha 35 C# - Interfaces: An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract. ➢ Like abstract classes, interfaces cannot be used to create objects ➢ Interface methods do not have a body - the body is provided by the "implement" class ➢ On implementation of an interface, you must override all of its methods ➢ Interfaces can contain properties and methods, but not fields/variables ➢ Interface members are by default abstract and public ➢ An interface cannot contain a constructor (as it cannot be used to create objects)
  • 36. C# Programming Prof. K. Adisesha 36 C# Enumerations: An enum is a special "class" that represents a group of constants (unchangeable/read- only variables). ➢ Enum is short for "enumerations", which means "specifically listed". ➢ To create an enum, use the enum keyword (instead of class or interface), and separate the enum items with a comma. ➢ By default, the first item of an enum has the value 0. The second has the value 1, and so on. ➢ Example: class Program { enum Level { Low, Medium, High } //You can access enum items with the dot syntax: static void Main(string[] args) { Level myVar = Level.Medium; Console.WriteLine(myVar); } }
  • 37. C# Programming Prof. K. Adisesha 37 C# - Exception Handling: An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. ➢ Exceptions provide a way to transfer control from one part of a program to another. ➢ C# exception handling is built upon four keywords: ❖ try ❖ catch ❖ finally ❖ throw try { // statements causing exception } catch( ExceptionName e1 ) { // error handling code } catch( ExceptionName e2 ) { // error handling code } catch( ExceptionName eN ) { // error handling code } finally { // statements to be executed }
  • 38. C# Programming Prof. K. Adisesha 38 C# - Exception Handling: A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. ➢ try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks. ➢ catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. ➢ finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. ➢ throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
  • 39. C# Programming Prof. K. Adisesha 39 C# - File I/O: A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. ➢ The stream is basically the sequence of bytes passing through the communication path. ➢ There are two main streams: the input stream and the output stream. ❖ The input stream is used for reading data from file (read operation). ❖ The output stream is used for writing into the file (write operation). ➢ The File class from the System.IO namespace, allows us to work with files. ➢ Example: using System.IO; // include the System.IO namespace File.SomeFileMethod(); // use the file class with methods
  • 40. Discussion Prof. K. Adisesha 40 Queries ? Prof. K. Adisesha 9449081542