0% found this document useful (0 votes)
6 views117 pages

C# Programming - Unit I

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
6 views117 pages

C# Programming - Unit I

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 117

C# .

NET Programming

UNIT – I

Class : II B.Sc. Computer Technology

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Unit I - Syllabus

Understanding .NET: The C# environment - Over


view of C# - Control statements - Methods in C#
- Classes and Objects - Categories of Class
Members - Adding variables -Adding methods-
creating objects - Access Modifiers

Dr. NGPASC
COIMBATORE | INDIA
Introducing C#
What is C#
 C# (pronounced "C-sharp") is an object-oriented
programming language from Microsoft
 C# aims to combine the computing power of C++ with
the programming ease of Visual Basic.
 C# is a fully object oriented language and it is a first
Component Oriented Language.
 C# is designed to support the key features of .NET
framework

Dr. NGPASC
COIMBATORE | INDIA
Highlights of C#
 It is a brand new language derived from the C /C++
family
 It is simple and modernizes C++
 It is the only component based language
 It is the only language designed for the .Net framework
 It is concise ,learn and modern language
 It combines the best features of many languages : the
productivity of Java, the power of C++ , and the
elegance of java
 It is intrinsically object –oriented and web enabled
 It has a lean and consistent syntax
 It is simple, productive and robust language
 Major part of .NET frame work are actually coded in C#
Dr. NGPASC
COIMBATORE | INDIA
Why C#
 C and C++ have been the two most popular and most
widely used languages in the software industry , but it
suffer from a number of shortcomings in the emerging
WWW requirement

Dr. NGPASC
COIMBATORE | INDIA
Why C#
 Visual Basic a language promoted by Microsoft for
overcoming these problems also could not meet the
requirement of the WWW
 Java language derived from C/C++ , is truly object
oriented and has been widely used for web
programming.
 Microsoft decided to design a new language C# , a
simple , modern language that directly addresses the
needs of component based software development

Dr. NGPASC
COIMBATORE | INDIA
Understanding .NET : The C#
 Environment
Microsoft wanted to make WWW more vibrant by
enabling individual devices, computer and web service
to work together

 By the intelligent integration of web sites on the


internet , users can create a wide variety of value
based applications such as unified banking services,
electronic bill ,payment, stock trading , insurance
service etc. Microsoft calls this Web Services.

 .NET is a software framework that includes everything


required for developing software for web services

Dr. NGPASC
COIMBATORE | INDIA
Microsoft .NET Strategy

Dr. NGPASC
COIMBATORE | INDIA
The Origins of .NET Technology
OLE Technology
 OLE object Linking and Embedding
enable easy inter-process communication
COM Technology
 Component Object Model the monolithic
approach had been used for developing
software.
 In this approach leads to number of
problems in terms of maintainability
and testing of software
 The component approach, a program is
broken into number of independent
components
NET Technology
 Replaced by intermediate language
called Microsoft Intermediate Language
(MSIL) or IL
 .Net compiler enforce inter-operability
by compiling code into IL
 characteristic of IL code is metadata
Dr. NGPASC
COIMBATORE | INDIA  IL allows for true cross language
integration
The .NET Framework
 The .NET Framework is one the tools provided by the .NET infrastructure
and tools component of the .NET platform
 The .NET framework provides an environment for building ,deploying and
running web services and other applications
Various Components of .NET Platform

It consist of three distinct technology


 Common Language Runtime (CLR)
 Framework Base Classes
 User and Program interfaces
(ASP.NET and Winforms)

Dr. NGPASC
COIMBATORE | INDIA
The .NET Framework
 The .NET Framework is one the tools provided by the .NET infrastructure
and tools component of the .NET platform
 The .NET framework provides an environment for building ,deploying and
running web services and other applications
Various Components of .NET Platform
It consist of three distinct technology
 Common Language Runtime (CLR)
 Framework Base Classes
 User and Program interfaces
(ASP.NET and Winforms)

Dr. NGPASC
COIMBATORE | INDIA
Common Language Runtime (CLR)
 The Common Language Runtime known as CLR is the heart and soul of the
.Net framework
 It supports cross language interoperability

Components of CLR

Dr. NGPASC
COIMBATORE | INDIA
CLR Activities
 CLR Activities that go on when an
applications is executed. The
source code is compiled to IL while
the metadata engine creates
metadata information

 IL and metadata are linked with


other native coded if required and
the resultant IL code is saved

 The IL code and any requirement


from the base class library are
brought together by the class
loader

 The combined code is tested for


type-safety and then compiled by
the JIT compiler to produce native
machine code , which is sent to the
Dr. NGPASC
runtime manager for execution
COIMBATORE | INDIA
CLR Activities

 Common Type System(CTS)


 .NET framework provides multiple language support using the features
known as Common Type System that is built into the CLR
 CTS supports a variety of types and operations , does not require type
conversion
 Common Language Specification (CLS)
 Define a set of rules that enables interoperability on the .NET platform
 Rules Serves as guide to third party compiler designers and library
builders
 The CLS is the subset of CTS
 API are designed following the rules of CLS can easily be used all
the .NET languages
Dr. NGPASC
COIMBATORE | INDIA
CLR Activities
 Microsoft Intermediate Language(MSIL)
 MISL is an instruction set into which all the .NET programs are
compiled
 It is similar to assembly language and contains instructions for
loading , storing
 Initializing and calling methods
 The C# source code is compiled into MSIL
 Managed Code
 CLR is responsible for managing the execution of code compiled for the
.NET
 Platform.
 The code that satisfies the CLR at runtime in order to execute is
referred to as managed code.
Dr. NGPASC
 The managed
COIMBATORE code generated by C# is IL code.
| INDIA
Framework Base Classes
 The base framework classes resides in the vast namespace called
System

User and Program Interface

Dr. NGPASC
COIMBATORE | INDIA
Overview of C#
C#
Program
C# used to develop two s
categories of programs
Executable application Executabl
Library
programs e
Component Libraries Programs Programs
Executable programs are
written to carry out certain
tasks and require the method CLR Application
Program
Main in one of the classes
Component Libraries do not
require a Main declaration Output
CLR

Output
Dr. NGPASC
COIMBATORE | INDIA
A Simple C# program
Class declaration
Class Declaration
Syntax :Class classname

The Braces  Example: class sample

The Main Method  C# is a true object


oriented language ,
everything must be
Executing the progrm placed inside the class

 Class is a keyword ,
The Output Line sample is a C# identifier
that specifies the name of
the class to be defined

Dr. NGPASC
COIMBATORE | INDIA
A Simple C# program
The Braces
C# is a block structured language , it means code blocks are always
enclosed by braces { and }.
Every class definition in C# begins with an opening brace { and end
with closing brace }
The Main Method
Syntax : public static void Main()

static: It means Main Method can be called without an object.


public: It is access modifiers which means the compiler can execute
this from anywhere.
void: The Main method doesn’t return anything.
Main(): It is the configured name of the Main method.
String []args: For accepting the zero-indexed command line
arguments. args is the user-defined name.

Dr. NGPASC
COIMBATORE | INDIA
A Simple C# program
The Output Line

Dr. NGPASC
COIMBATORE | INDIA
A Simple C# program
Executing the Program

C# Code (.cs file)

C# Compilation

IL Code (.exe file)

JIT Compilation

Native Machine
Code
Execution

Output

Dr. NGPASC
COIMBATORE | INDIA
Adding Comments
A comment is preceded by an double forward slash. The
code of line after the double forward slash is simply
ignored by the compiler.
 Single line comments - // for single line
comments
 Multiple line comments - /* for multi line comments
*/ // This is an example of
 Example
// multiline comments
// in C# language
/* …………………………………
/* usign System;*/
…………………………………….
*/

Dr. NGPASC
COIMBATORE | INDIA
Program Structure
Documentation section Using directive section will include all those
namespaces that contain classes required by the application
An Interface section similar to class by contain only abstract
members. It is used to implement multiple inheritance
C# contain multiple class definitions. Classes are primary and
essential elements of a program
 Main method is a starting

Documentation
Section
Directive Section
Optional
Interface Section

Classes Section

Main() Method Essentia


Section l
Dr. NGPASC
COIMBATORE | INDIA
Program Structure – Example

Dr. NGPASC
COIMBATORE | INDIA
Main Returning a Value
// Main returning a value
using System;
class Sampleone
{
public static int Main(String args[])
{
Console.WriteLine(“Hello”);
return 0;
}
}

Dr. NGPASC
COIMBATORE | INDIA
Using Aliases for Namespace
Classes
Using Aliases for Namespace Classes
System is a name space and console is a class. The using
directive can be applied only to namespace and cannot
be applied to classes
using alias name = class-name
Example
Using A=System.Console;// A is alias for System.Console
class Sampleone
{
public static void Main(String args[])
{
A.WriteLine(“Hello”);
}
}
Dr. NGPASC
COIMBATORE | INDIA
Passing String objects to WriteLine
Method

using System;
class Sampletwo
{
public static void Main( )
{
String name = “C Sharp”;
Console.WriteLine(name);
}
}

Dr. NGPASC
COIMBATORE | INDIA
Command Line Arguments
Input provided at the time of execution , C# by using command line
arguments.
Command line arguments are parameters supplied to the Main
method at the time of execution

Dr. NGPASC
COIMBATORE | INDIA
Main with a Class

Dr. NGPASC
COIMBATORE | INDIA
Literals, Variables and Data Types
A C# program is basically a collection of classes.
A Class is defined by a set of declaration, statements, and methods
containing instruction known as executable statements
These instructions are formed using certain symbols and words to some
rigid rules known as syntax rules or grammar.
The smallest , non-reducible , textual elements in a program are referred to
as tokens
C# program is a collection of tokens , comments and white space
There are five types of tokens:
Keywords
Identifiers
Literals
Operators
Punctuators
White space and comments are not tokens

Dr. NGPASC
COIMBATORE | INDIA
Keywords
 It is a reserved word, it cannot be used as identifiers except when they are
prefaced by the @ character

abstract as base bool params throw public


break byte case catch readonly uint sbyte
char checked class const sealed ushort stackalloc
continue decimal default delegate static volatile switch
do double else enum this protected try
unchecke
event explicit extern false typeof return
d
using
finally fixed float for unsafe sizeof
static
foreach goto if implicit void struct
in
in (generic int interface private true
modifier)
internal is lock long ref ulong
namespac
new null object short using
e
Dr. NGPASC out
COIMBATORE | INDIA
operator out (generic override string while
Identifiers
 Identifiers are programmer designed tokens.They are used for naming
classes, methods , variables , labels, namespaces , interfaces etc
C# identifiers enforce the following rules
 They can have alphabets , digits and underscore characters
 They must not begin with a digit
 Uppercase and lower case letters are distinct
 Keywords in stand-alone mode cannot be uses as identifiers
C# permits the use of keywords and identifiers when they are prefixed with
the @ character
Identifiers Remarks
number Valid

hello$ Invalid (Contains $)

name1 Valid

@if Valid (Keyword with prefix @)

if Invalid (C# Keyword)

My name Invalid (Contains whitespace)

_hello_hi Valid
Dr. NGPASC
COIMBATORE | INDIA
Literals
 Literals are in which the values that are stored in variables are represented

Dr. NGPASC
COIMBATORE | INDIA
Backslash Character Literals
Backslash character Literals are used in output methods.
Example : ‘\n’ – new line character, Each one represents on character
although they consist of two characters
These character combinations are known as escape sequences

Dr. NGPASC
COIMBATORE | INDIA
Literals Example
using System;
class Literalexample {
public static void Main(String []args)
{
int a = 101;
int b = 0145; // octal-form literal
Console.WriteLine(a);
Console.WriteLine(b);
double a = 101.230;
Console.WriteLine(a);
char ch = 'a';
Console.WriteLine(ch);
String s = "Hello III CT B!";
Console.WriteLine(s);
bool b = true;
bool c = false;
Console.WriteLine(b);
Console.WriteLine(c);
} }

Dr. NGPASC
COIMBATORE | INDIA
Variables
 A variables is an identifiers that denotes a storage location used to store a
data value
Variables are changed during the execution of a program
A variable may take different values at different times during execution of
the program
Example : Variable name can be chosen by the programmer in a
meaningful : Average, height
Variable follows the below conditions
 They can have alphabets , digits and underscore characters
 They must not begin with a digit
 Uppercase and lower case letters are distinct
 Keywords in stand-alone mode cannot be uses as identifiers
 White space is not allowed
 Variable names can be of any length
Syntax type variableName = value;

Example int myNum = 99 ;

Dr. NGPASC
COIMBATORE | INDIA
Data Types
 C# is a language rich in its data types
 Types in C# are primarily divided into two categories
 Value type
 Reference type
 Third category of types called Pointer – is available for use only in unsafe
code

Dr. NGPASC
COIMBATORE | INDIA
Data Types

Value Type Reference Type


Stored on the stack Stored on the heap
When a value of a variable is assigned When an assignment between two
to another variable the value is actually reference variables occurs only the
copied reference is copied
Two identical copies of the values are The actual value remains in the same
available in memory memory locations
Value type is classified into predefined Reference type is classified into
and user defined types predefined and user defined types

Dr. NGPASC
COIMBATORE | INDIA
Data Types
Example: Value Type

Example: Reference Type

Dr. NGPASC
COIMBATORE | INDIA
Data Types – Value Type
 The value types of C# can be grouped into two categories
 User-defined types or complex types – includes struct and
enumerations
 Predefined types or simple types – includes Numeric , Boolean and
Character type

Dr. NGPASC
COIMBATORE | INDIA
Data Types – Value Type
 Predefined types or simple types

Type Description
byte 8-bit unsigned integer
sbyte 8-bit signed integer
short 16-bit signed integer
ushort 16-bit unsigned integer
int 32-bit signed integer
uint 32-bit unsigned integer
long 64-bit signed integer
ulong 64-bit unsigned integer
float 32-bit Single-precision floating point type
double 64-bit double-precision floating point type
128-bit decimal type for financial and monetary
decimal
calculations
char 16-bit single Unicode character
bool 8-bit logical true/false value
object Base type of all other types.
string A sequence of Unicode characters
DateTime Represents date and time

Dr. NGPASC
COIMBATORE | INDIA
Data Types – Value Type
 Predefined types or simple types
Types Memory Size
char 1 byte
signed char 1 byte
unsigned char 1 byte
short 2 byte
signed short 2 byte
unsigned short 2 byte
int 4 byte
signed int 4 byte
unsigned int 4 byte
long 8 byte
signed long 8 byte
unsigned long 8 byte
float 4 byte
double 8 byte
decimal 16 byte
Dr. NGPASC
COIMBATORE | INDIA
Data Types – Reference Type
 The reference types can also be divided into two groups
 User-defined types or complex types – includes Classes , Interface,
Delegates and Arrays
 Predefined types or simple types – includes Object type and String type
 The object type is the ultimate base type of all other intrinsic and user
defined types in C#. Use an object reference to bind an object of any
particular type
 Use the object type to convert to value type on the stack to an object type
to be placed on the heap
 C# provides its own string type for creating and manipulating strings

Dr. NGPASC
COIMBATORE | INDIA
Default values
 A variable is either explicitly assigned a value or automatically assigned a
default value
 The following categories of variables are automatically initialized to their
default values:
 Static variables
 Instance Variables
 Array variables

Dr. NGPASC
COIMBATORE | INDIA
Constant Variables
 The variables whose value do not
change during the execution of a
program are known as constants
 Variables can be made un-
modifiable by using the const
keyword while initializing them
 Example : const int Rows=10;
 A constant variable can be
initialized using an expression
 Example : const int m=10;
const int n=m*5;
 Advantages of using constant
are:
 Programs easier to read and
understand
 Program easier to modify
 They minimize accidental errors

Dr. NGPASC
COIMBATORE | INDIA
Scope of Variables
 The scope of a variables is the region of code within which the variable
can be accessed.
 C# defines several categories of variables
 They include:
 Static variables
 Instance variables
 Array elements
 Value parameters
 Reference parameters
 Output parameters
 Local variables
 Example

Dr. NGPASC
COIMBATORE | INDIA
Boxing and Unboxing
 Boxing is used to store value types in the garbage-collected heap.
 Boxing is an implicit conversion of a value type to the type object or to
any interface type implemented by this value type.
 Boxing a value type allocates an object instance on the heap and copies
the value into the new object.
 Consider the following declaration of a value-type variable:
int i = 123;
// Boxing copies the value of i into object o.
object o = i;
 The result of this statement is creating an object reference o, on the
stack, that references a value of the type int, on the heap.
 This value is a copy of the value-type value assigned to the variable i.
 The difference between the two variables, i and o, is illustrated in the
following figure.

Dr. NGPASC
COIMBATORE | INDIA
Boxing and Unboxing
 Boxing Conversion
 It is also possible to perform the boxing explicitly as in the following
example, but explicit boxing is never required:
int i = 123;
object o = (object)i; // explicit boxing
• Example
class TestBoxing {
static void Main() {
int i = 123;
object o = i; // Boxing copies the value of i into object
o
i = 456; // Change the value of i.
// The change in i does not effect the value stored in o.
System.Console.WriteLine("The value-type value = {0}", i);
System.Console.WriteLine("The object-type value = {0}",
o);
} }
/* Output:
The value-type value = 456
The object-type value = 123
Dr.*/
NGPASC
COIMBATORE | INDIA
Boxing and Unboxing
 UnBoxing
 Unboxing is an explicit conversion from the type object to a value type or
from an interface type to a value type that implements the interface.
 An unboxing operation consists of:
 Checking the object instance to make sure that it is a boxed value of the
given value type.
 Copying the value from the instance into the value-type variable.
 The following statements demonstrate both boxing and unboxing
operations:
int i = 123; // a value type
object o = i; // boxing
int j = (int)o; // unboxing
 The following figure demonstrates the result of the previous statements.

Dr. NGPASC
COIMBATORE | INDIA
Boxing and Unboxing
 UnBoxing Example
class TestUnboxing
{
static void Main()
{
int i = 123;
object o = i; // implicit boxing
try
{
int j = (short)o; // attempt to unbox
System.Console.WriteLine("Unboxing OK.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect unboxing.",
e.Message);
}
}
}

Dr. NGPASC
COIMBATORE | INDIA
Operators and Expression
 An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations
 Operators are used in programs to manipulate data and variables
 C# supports a rich set of operators

Dr. NGPASC
COIMBATORE | INDIA
Operators and Expression
 Arithmetic Operator
 Three types of Arithmetic Operation
 Integer Arithmetic
 Real Arithmetic
 Mixed Mode Arithmetic

Operator Meaning Example


+ Addition or unary plus a+b
- Subtraction or unary minus a-b
* Multiplication a*b
/ Division a/b
% Modulo division a%b
a and b may be variables or constants are
known as operands

Dr. NGPASC
COIMBATORE | INDIA
Operators and Expression
Relational Operators

Logical Operators

Dr. NGPASC
COIMBATORE | INDIA
Operators and Expression
Assignment Operators : Syntax : Variable op=expression

Increment and Decrement Operators (++ and --)

Dr. NGPASC
COIMBATORE | INDIA
Operators and Expression
 Conditional Operator
 The character pair ?: is a ternary operator .
Syntax : exp1 ? exp2 :exp3
 Where exp1,exp2 and exp3 are expression
 Exp1 is evaluated first , if it is true , then the expression exp2 is
evaluated otherwise expression exp3 is evaluated
 Example x=(a>b) ? a:b;
 Bitwise Operator
 Bitwise operator may be used for manipulation of data at bit level
 These operator may be used for testing the bits or shifting them to the
right or left
 Bitwise operator may not be applied to floating point data

Dr. NGPASC
COIMBATORE | INDIA
Operators and Expression
 Special Operators

Dr. NGPASC
COIMBATORE | INDIA
Operators and Expression
 Arithmetic Expressions
 An arithmetic expressions is a combination of variables, constants and
operators arranged as per the syntax of the language

Dr. NGPASC
COIMBATORE | INDIA
Expression
 Evaluation of Expressions
 Expressions are evaluated using an assignment statement of the form
Variable =expression;
 When the statement is encountered the expression is evaluated first and
the result then replaces the previous value of the variable on the left
hand side
 Example : x=a*b-c;
 Precedence of Arithmetic Operators
 An arithmetic expression without any parentheses will be evaluated form
left to right using the rules of precedence of operators
High priority : * , / , %
Low priority : + , -
 When the parentheses are used , the expression within parentheses
assume highest priority
 Example x=9-12/3+3*2-1 -- result x=10 (Expression without
parentheses)
 Example x=9-12/(3+3)*(2-/) -- result x=7 (Expression with
parentheses)

Dr. NGPASC
COIMBATORE | INDIA
Type Conversions
 Type Conversions
 To convert data of one type to
another
 In C# type conversion take
place in two ways
 Implicit conversion
 Explicit conversion
 Implicit Conversion
 An implicit conversion is
known as automatic type
conversion
 The conversion can always be
performed without any loss of
data
 Example : short b =75;
 The processint a=b;
of assigning a smaller type to a larger one is known as
widening or promotion
 The process of assigning a larger type to a smaller one is known as
narrowing
Dr. NGPASC
COIMBATORE | INDIA
Type Conversions
 Explicit Conversion
 Explicitly carry out such conversions using the cast operator. The
process is known as casting
 Syntax : type variable1=(type) variable 2;
 Casting into a smaller type may result in loss of data
 Example :
int m=50;
byte n=(byte)m;
 C# provides methods to convert between numeric values and strings
 Example: int m=100;
 String s=m.Tostring();
 C# provides methods to convert between string and integer values
 Example: string m= “100”;
 int n=int.Parse(m);

Casting in
Expressions
Use of casts

Dr. NGPASC
COIMBATORE | INDIA
Operator Precedence and Associativity

Dr. NGPASC
COIMBATORE | INDIA
Operator Precedence and Associativity

Dr. NGPASC
COIMBATORE | INDIA
Mathematical Functions
Mathematical Functions
The System namespace defines a class known as Math class with a rich
set of static methods that makes math oriented programming easy and
efficient
Example
using system;
class mathtest
{
public static void main()
{
Console.WriteLine(“ Enter the x value”);
Double x=double.parse(Console.ReadLine());
Console.WriteLine(“ Sin value=”+Math.Sin(x));
Console.WriteLine(“ Log value=”+Math.Log(x));
Console.WriteLine(“ Absolute value=”+Math.Abs(x));
Console.WriteLine(“ tan value=”+Math.Tan(x));
}
}

Dr. NGPASC
COIMBATORE | INDIA
Mathematical Functions

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Decision Making
statements:
Decision making structures requires
the programmer to specify one or
more conditions to be evaluated or
tested by the program, along with a
statement or statements to be
executed if the condition is determined
to be true, and optionally, other
statements to be executed if the
condition is determined to be false.

C# provides following types of


decision making statements:
Simple if statement
if...else statement
nested if statement
else if ladder statement
Ternary Operator or Conditional
Operator
Dr. NGPASC
switch statement
COIMBATORE | INDIA
Control Statements

Simple if Statement:
An if statement consists of a boolean
expression followed by one or more
statements.
Syntax
if(condition)
{
// block of code
}
If the condition evaluates to true,
then the block of code inside the if
statement is executed.
 If condition evaluates to false, then
the first set of code after the end of
the if statement is executed.

Dr. NGPASC
COIMBATORE | INDIA
Control Statements

Simple if Statement:
An if statement consists of a boolean
expression followed by one or more
statements.
Syntax
if(condition)
{
// block of code
}
If the condition evaluates to true,
then the block of code inside the if
statement is executed.
 If condition evaluates to false, then
the first set of code after the end of
the if statement is executed.

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Simple if Statement: Example
using System;
class simpleif
{
static void Main(string[] args)
{
int a = 10;
if (a < 20)
{
Console.WriteLine("a is less
than 20");
} a is less than
Console.WriteLine("value of a is : 20
{0}", a); value of a is :
Console.ReadKey(); 10
}
}
}

Dr. NGPASC
COIMBATORE | INDIA
Control Statements

If.. Else Statement:


An if statement can be followed by
an optional else statement, which
executes when the boolean expression
is false.
Syntax
if(condition)
{
// true block of code
}
else
{
// false block of code
}
If the condition evaluates to true,
then the if block of code is executed,
otherwise else block of code is
executed.
Dr. NGPASC
COIMBATORE | INDIA
Control Statements
If.. else Statement: Example
using System;
class ifelsetest
{
static void Main(string[] args)
{
int a = 100;
if (a < 20)
{
Console.WriteLine("a is less than 20");
}
else a is not less than
{ 20
Console.WriteLine("a is not less than value of a is :
20"); 100
}
Console.WriteLine("value of a is :
{0}", a);
Console.ReadKey();
} NGPASC
Dr. }}
COIMBATORE | INDIA
Control Statements
Nested if Statement:
if statement inside an if statement is known as nested if. if statement
in this case is the target of another if or else statement.
When more then one condition needs to be true and one of the
condition is the sub-condition of parent condition, nested if can be used.
Syntax:
if (condition1)
{
// code to be executed
if (condition2)
{
// code to be executed
}
}

Dr. NGPASC
COIMBATORE | INDIA
Control Statements

Nested .. If else statement


using System;
class nestedif {
public static void Main(String[] args)
{
int i = 10;
if (i == 10)
{
if (i < 12)
Console.WriteLine("i is smaller
than 12 ");
else
Console.WriteLine("i is greater
than 15");
}
}
}
i is smaller than 12
Dr. NGPASC
COIMBATORE | INDIA
Control Statements
If – else – if ladder Statement:
The if-else-if ladder statement executes one condition from multiple
statements. The execution starts from top and checked for each if
condition.
The statement of if block will be executed which evaluates to be true.
If none of the if condition evaluates to be true then the last else block is
evaluated.
Syntax:
if(condition1)
{
// code to be executed if condition1 is true
}
else if(condition2)
{
// code to be executed if condition2 is true
}
else if(condition3)
{
// code to be executed if condition3 is true
} NGPASC
Dr. ……
COIMBATORE | INDIA
Control Statements
using System;
class ifelseladder {
public static void Main(String[] args)
{
int i = 20;

if (i == 10)
Console.WriteLine("i is 10");
else if (i == 15)
Console.WriteLine("i is 15");
else if (i == 20)
Console.WriteLine("i is 20");
else
Console.WriteLine("i is not
present");
}
}

i is 20
Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Switch statement:
Switch statement is an alternative to long if-else-if ladders.
 The expression is checked for different cases and the one match is
executed. break statement is used to move out of the switch. The
expression used in a switch statement must have an integral or
enumerated type, or be of a class type
If the break is not used, the control will flow to all cases below it until
break is found or switch comes to an end.
There is default case (optional) at the end of switch, if none of the case
matches then default case is executed.
Any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Switch
statement:Syntax:
switch (expression)
{
case value1: // statement
sequence
break;

case value2: // statement


sequence
break;

……………..
……………..
……………..

case valueN: // statement


sequence
break;
Dr. NGPASC
COIMBATORE | INDIA
default: // default statement
Control Statements
Switch
statement:Syntax:
switch (expression)
{
case value1: // statement
sequence
break;

case value2: // statement


sequence
break;

……………..
……………..
……………..

case valueN: // statement


sequence
break;
Dr. NGPASC
COIMBATORE | INDIA
default: // default statement
Control Statements
Switch statement:
using System;
public class switchtest
{
public static void Main(String[] args)
{
int number = 30;
switch(number)
{
case 10: Console.WriteLine("case 10");
break;
case 20: Console.WriteLine("case 20");
break;
case 30: Console.WriteLine("case 30");
break;
default: Console.WriteLine("None case 30
matches");
break;
}
}}
Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Ternary Operator ( ?: )
C# includes a decision-making operator ?: which is called the conditional
operator or ternary operator. It is the short form of the if else conditions.
Syntax:
condition ? statement 1 : statement 2
The ternary operator starts with a boolean condition.
If this condition evaluates to true then it will execute the first statement
after ?, otherwise the second statement after : will be executed.
Example: Ternary operator
using System;
class Ternary
{ public static void Main(string[] args)
{
int number = 2;
bool isEven;
isEven = (number % 2 == 0) ? true : false ;
Console.WriteLine(isEven);
} }

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Looping statements:
A loop statement allows us to execute a statement or a group of
statements multiple times
The loops in C# are basically of two types depending on their behavior.
These are:
Entry controlled loop: When the looping condition is checked at the
very beginning of the loop body and before executing the loop block,
those types of looping statements are termed as entry controlled loops.
There are two types of looping statements provided by C# that is entry
controlled.
Exit controlled loop: When the looping condition is checked at the
end of the loop body and right after executing the loop block (at least
once), those types of looping statements are termed as exit controlled
loops. C# provides only one exit controlled looping statement, and that
is the do-while loop.
C# provides following types of loop
1. while loop
2. do...while loop
3. for loop
4. for..each loop
Dr. NGPASC
COIMBATORE | INDIA
Control Statements
While Loop:
C# provides the while loop to repeatedly execute a block of code as
long as the specified condition returns false.
Syntax:
while(condition)
{
//code block
}
The while loop starts with the while keyword, and it must include a
boolean conditional expression inside brackets that returns either true or
false. It executes the code block until the specified conditional
expression returns false.
When using the while loop, initialization should be done before the loop
starts, and increment or decrement steps should be inside the loop.

Dr. NGPASC
COIMBATORE | INDIA
Control Statements

While Loop:
Example: i = 0
using System; i = 1
class whiletest i = 2
{ i = 3
public static void Main() i = 4
{ i = 5
int i = 0; i = 6
while (i < 10) i = 7
{ i = 8
Console.WriteLine("i = {0}", i); i = 9
i++;
}
}
}

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Do..While Loop:
The do while loop is the same as while loop except that it executes the
code block at least once.
Syntax:
do
{
//code block
} while(condition);
The do-while loop starts with the do keyword followed by a code block
and a condition with the while keyword.
The do while loop stops execution exits when a condition evaluates to
false. Because the while(condition) specified at the end of the block, it
certainly executes the code block at least once.

Dr. NGPASC
COIMBATORE | INDIA
Control Statements

Do..While Loop:
Example:
using System;
class dowhiletest
{
public static void Main() i = 0
{ i = 1
int i = 0; i = 2
do i = 3
{ i = 4
Console.WriteLine("i = {0}", i);
i++;

} while (i < 5);


}}

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
For Loop:
The for keyword indicates a loop in C#. The for loop executes a block
of statements repeatedly until the specified condition returns false.
Syntax:
for (initializer; condition; iterator)
{
//code block
}
The for loop contains the following three optional sections, separated
by a semicolon:
Initializer: The initializer section is used to initialize a variable that
will be local to a for loop and cannot be accessed outside loop. It can
also be zero or more assignment statements, method call, increment, or
decrement expression e.g., ++i or i++, and await expression.
Condition: The condition is a boolean expression that will return
either true or false. If an expression evaluates to true, then it will
execute the loop again; otherwise, the loop is exited.
Iterator: The iterator defines the incremental or decremental of the
loop variable.
Dr. NGPASC
COIMBATORE | INDIA
Control Statements

For Loop:
Example: Value of i: 0
using System; Value of i: 1
class fortest Value of i: 2
{ Value of i: 3
public static void Main() Value of i: 4
{ Value of i: 5
for(int i = 0; i < 10; i++) Value of i: 6
{ Value of i: 7
Console.WriteLine("Value of i: {0}", i); Value of i: 8
}}} Value of i: 9

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Foreach Loop:
foreach loop is used to iterate over the elements of the collection.
The collection may be an array or a list.
It executes for each element present in the array.
It is necessary to enclose the statements of foreach loop in curly
braces {}.
Instead of declaring and initializing a loop counter variable, you
declare a variable that is the same type as the base type of the array,
followed by a colon, which is then followed by the array name.
In the loop body, you can use the loop variable you created rather than
using an indexed array element.
Syntax
foreach (type variableName in arrayName)
{
// code block to be executed
}

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Foreach Loop
Example:
using System;
class foreachtest
{ public static void Main()
{
string[] cars = {"Volvo",
"BMW",
"Ford",
"Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
}
.

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
JUMP
The following statements are used to pass control

Statemen
Description
t
It stops the nearest control statement to its
break; location, and passes control to the next
statement, if it exists.
It passes control to the next iteration of the
continue;
control statement where it is located.
It stops execution of the method, and returns a
return;
value(optional).
goto It transfers control to a specified statement.

Dr. NGPASC
COIMBATORE | INDIA
Control Statements
Example: continue Example: goto
using System; using System;
class abc class abc
{ { public static void Main()
public static void Main() {
{ int i = 1;
int i = 1; for(i = 0; i < 12; i++)
while (i < =10) {
{ if(i==10)
if(i==5) {
{ goto entry;
continue; }
} else
Console.WriteLine(i); {
i++; Console.WriteLine(i);
} }
} entry:
} Console.WriteLine("Hello
Goto!!!”);
Dr. NGPASC
} }}
COIMBATORE | INDIA
C# .NET Programming
Classes and Object
 C# is a true object oriented language and therefore the
underlying structure of all C# programs is classes
 A class is a user-defined blueprint or prototype from
which objects are created.
 A class combines the fields and methods into a single unit.
 In C#, classes support polymorphism, inheritance and also
provide the concept of derived classes and base classes.

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Classes and Object
 Classes provide a convenient approach for packing together
a group of logically related data items and functions that
work on them
 In C# the data items are called fields, the functions are
called methods
 Calling a specific method in an object is described as sending
the object a message

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Classes and Object
 All object oriented languages employ three core principles
1. Encapsulation -:
 Provides the ability to hide the internal details of an
object from its user
 Outside user may not be able to change the state of an
object directly , may be indirectly using accessor or and
mutator methods
 C# encapsulation is implemented using the access
modifier keywords public, private and protected
 Encapsulation is also known as data hiding or
information hiding

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Classes and Object
2. Inheritance-:
 It is the concept use to build new classes using the
existing class definitions
 The original class is known as base or parent class and the
modified one is known as derived class or subclass or
child class
 Inheritance facilities the reusability of existing code and
improve the integrity and productivity of programmers

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Classes and Object
3. Polymorphism -:
 Polymorphism is the third concept , it is the ability to take
more than one form

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Defining a Class
 A Class is a user defined data type with a template that
serves to define its properites
 Variables are termed as instances of classes which are the
actual objects
 Keyword class: A class
keyword is used to declare
the type class
 Class name : any valid
C# identifier
 Modifiers: A class can be
public or internal etc. By
default modifier of class is
internal.
 Body: The class body is
surrounded by { } (curly
Dr. NGPASC braces).
COIMBATORE | INDIA
C# .NET Programming
Categories of Class Members

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Adding Variables
 Data is encapsulated in a class by placing data fields inside the body of the
class definition. These variables are called instance variables
 Instance variables are known as member variables
 Example

 These variables are only declared and therefore no storage space has been
created in the memory

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Adding Methods
 A class with only data fields and without methods that operate on that data
has no life
 The objects created by such a class cannot respond to any messages
 Method are necessary for manipulating the data contained in the
classExample

Example
Example

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Member Access Modifiers

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Accessibility Table
protecte protected private
public internal private
d internal protected
Entire program Yes No No No No No

Containing class Yes Yes Yes Yes Yes Yes

Current assembly Yes No Yes Yes No No

Derived types Yes Yes No Yes No No

Derived types
within current Yes Yes Yes Yes No Yes
assembly

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Creating Objects
 An object is essentially a block of memory that contains
space to store all the instance variables
 Creating an object is also referred to as instantiating an
object
 Object in C# are created using the new operator
 The new operator creates an object of the specified class and
returns a reference to that object

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Creating Objects
Creating object
reference

Accessing one object


reference variable to
another

Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Accessing Class Members

To access the member


outside the class we
must use the concerned
object and the dot
operator
The instance variblae of
the Rectangle class may
be accessed and
assigned values

Two objects rect1 and


rect2 store different
values
Dr. NGPASC
COIMBATORE | INDIA
C# .NET Programming
Classes and Object Example
class Car
{
string color = "red";

static void Main(string[] args)


{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}

red

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Methods in C#
A method is a group of statements that together perform a task.
Every C# program has at least one class with a method named Main.
To use a method, you need to −
 Define the method
 Call the method
 Defining Methods in C#
Syntax
<Access Specifier><Return Type><Method Name>(Parameter List)
{
Method Body
}

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Following are the various elements of a method −
Access Specifier − This determines the visibility of a variable or a
method from another class.
Return type − A method may return a value. The return type is the data
type of the value the method returns. If the method is not returning any
values, then the return type is void.
Method name − Method name is a unique identifier and it is case
sensitive. It cannot be same as any other identifier declared in the class.
Parameter list − Enclosed between parentheses, the parameters are
used to pass and receive data from a method. The parameter list refers
to the type, order, and number of the parameters of a method.
Parameters are optional; that is, a method may contain no parameters.
Method body − This contains the set of instructions needed to
complete the required activity.

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as
variables inside the method
using System;
Class paramsargu
{
static void MyMethod(string fname)
{
Console.WriteLine(fname + " Refsnes");
}
static void Main(string[] args)
{
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
}
}

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Parameters and Arguments: Default Parameter Value
using System;
Class dparams
{
static void MyMethod(string country = "Norway")
{
Console.WriteLine(country);
}

static void Main(string[] args)


{
MyMethod("Sweden");
MyMethod("India");
MyMethod();
MyMethod("USA");
}
}

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Parameters and Arguments: Multiple Parameters

using System;
class mparams
{
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}

static void Main(string[] args)


{
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
}
}

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Return Values
The void keyword, used in the examples above, indicates that the
method should not return a value.
If you want the method to return a value, you can use a primitive data
type (such as int or double) instead of void, and use the return keyword
inside the method:
Example
using System;
class returntest
{
static int MyMethod(int x)
{
return 5 + x;
}

static void Main(string[] args)


{
Console.WriteLine(MyMethod(3));
}
} Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Passing Parameters to a Method
When method with parameters is called, you need to pass the
parameters to the method. There are three ways that parameters can be
passed to a method –
1. Value Parameter
This is the default mechanism for passing parameters to a method.
In this mechanism, when a method is called, a new storage location is
created for each value parameter.
The values of the actual parameters are copied into them. Hence, the
changes made to the parameter inside the method have no effect on the
argument

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Value Parameter int x = 500;
using System; int y = 700;
class valpar{ Console.WriteLine("Before
public int Valuepro(int x,int y) swapping");
{ Console.WriteLine("-----------------");
return (x * y); Console.WriteLine("X=" + x);
} Console.WriteLine("Y=" + y);
static void Main(string[] args) Console.ReadKey();
{ } }
valpar p = new valpar();
Console.WriteLine("Value Parameter");
int final = p.Valuepro(10, 20);
Console.WriteLine("Product value=" +
final);
Console.WriteLine("----------------------");
Console.WriteLine("Reference
Parameter");
Console.WriteLine("----------------------");

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Reference Parameter
It is a reference to a memory location of a variable. When you pass
parameters by reference, unlike value parameters, a new storage
location is not created for these parameters.
 The reference parameters represent the same memory location as the
actual parameters that are supplied to the method.
You can declare the reference parameters using the ref keyword

Example static void Main(string[] args)


using System; {
class refpar refpar p = new refpar();
{ p.referparam(ref x, ref
public void referparam(ref int y);
x,ref int y) Console.WriteLine("After
{ swapping");
int temp = x; Console.WriteLine("X=" + x);
x = y; Console.WriteLine("Y=" + y);
y = temp; Console.ReadKey();
} }
}
Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Output Parameter
A return statement can be used for returning only one value from a
function. However, using output parameters, you can return two values
from a function.
Output parameters are similar to reference parameters, except that
they transfer data out of the method rather than into it.
Example int m;
using System; p.square(10, out m);
class outpar Console.WriteLine("Square of a no="
{ + m);
public void square(int x, out int y) Console.ReadKey();
{ }
y = x * x; }
}
static void Main(string[] args)
{
outpar p = new outpar();
Console.WriteLine("Output
parameter");

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Params (params)
The ‘param’ keyword can be used to specify a method parameter
that takes a variable number of arguments.
When we use ‘param’ keyword to pass variable number of arguments
we can send any number of arguments or no arguments. But all the
arguments passed should be of same type.

Output Parameter static void Main(string[] args)


using System; {
class paramspar paramspar p = new paramspar();
{ Console.WriteLine("Parameter
public static void Array");
array(params int[] a) int[] arr = { 11, 12, 13, 14, 15 };
{ array(arr);
foreach (int i in a) Console.ReadKey();
{ }}
Console.WriteLine(i);
}

Dr. NGPASC
COIMBATORE | INDIA
Methods in C#
Output Parameter
using System;
class diffparameter
{
public static void array(params int[] a)
{
foreach (int i in a)
{
Console.WriteLine(i);

}
}
static void Main(string[] args)
{
diffparameter p = new diffparameter();
Console.WriteLine("Parameter Array");
Console.WriteLine("------------------------------------------------");
int[] arr = { 11, 12, 13, 14, 15 };
array(arr);
Console.ReadKey();
}

Dr. NGPASC
COIMBATORE | INDIA

You might also like