UNIT 2 - C# Notes
UNIT 2 - C# Notes
Topics
C# Tokens
• The smallest, non-reducible, textual elements in a program are referred to as tokens. The compiler
recognizes them for building up expressions and statements.
• C# includes 5 types of tokens:
• Keywords
• Identifiers
• Operators
• Literals
• Punctuators
Keywords
• Keywords are an essential part of programming language
• They implement specific features of the language
• They are reserved and cannot be used as identifiers except when they are prefixed with the @ character
C# Keywords
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 1
Identifiers
Operators
Operators are symbols used in expressions to describe operations involving one or more operands
Operators are used in programs to perform certain mathematical and logical operation
Operators are used to manipulate data and variables
C# supports a rich set of operators
C# operators are classified into various categories as below :
Arithmetic operators
Relational operators
Logical operators
Assignment operator
Inclement and Decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic Operators
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 2
Following are the arithmetic operators
• Used for comparing two quantities and depending on this relation take certain decisions
• Relational operators always result a Boolean value (true or false)
Operator Meaning Example (a=6, b=6)
< is less than a<b
<= is less than or equal to a <= b
> is greater than a>b
>= is greater than or equal to a >= b
== is equal to a == b
!= is not equal to a != b
Logical Operators
Logical operators are used when we want to form compound conditions by combining two or more
relations
An expression that combines two or more relational expressions is called as logical expressions or
compound relational expression
In other way, logical expression operates on Boolean operands
Operator Meaning
&& Logical ANDLogical
|| OR Logical NOT
Bitwise Logical OR
Truth Tables
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 3
Assignment Operators
C# has a set of shorthand assignment operators which are used in the form
v op= exp;
Where, v is a variable, „exp‟ is an expression and „op=‟ is a C# binary operator.
The operator „op=‟ is known as the shorthand assignment operator
Form Meaning
var++ (post increment) Use the value of the variable and increment by ‘1’ for later use
var-- (post decrement) Use the value of the variable and decrement by ‘1’ for later use
--var (pre decrement) Decrement the value of variable by ‘1’ and use
Conditional Operator
Conditional operator is a ternary operator
It is denoted by character pair ?:
It is used to construct conditional expression of the form exp1 ? exp2 : exp3
Where, exp1, exp2, and exp3 are expressions
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 4
It works as follows:
exp1 is evaluated first. If it is true, then the exp2 is evaluated and becomes the value of the
conditional expression. Else, exp2 is evaluated and becomes the value of the conditional expression.
Example:
a = 30 , b = 40
x = (a>b) ? a : b ;
Note: only one of the expressions (either exp2 or exp3) is evaluated. [Note: Refer Program to find
largest of two numbers]
Special Operators
C# supports the following special operators
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 5
Literals
Integer Literals
An integer literal refers to a sequence of digits
There are two types of integers, namely decimal integers and hexadecimal integers
Decimal integers consist of a set of digits 0 through 9, preceded by an optional minus sign
Example: 123, -256, 0, 56734
Hexadecimal integers consist of a set of digits 0 through 9 and alphabets A through F, preceded by
„0x‟ or „0X‟
Example: 0x2, 0XA19
Real Literals
The quantities that are represented by numbers containing fractional parts like
5.126 are called real (floating point) numbers.
Example: 3.142, 0.0067, -45.36
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 6
Boolean Literals
There are two Boolean literal values
True
False
They are used as
o values (result) of relational expressions
o Operands of Logical operations
Character Literals
Single character literal
It contains a single character enclosed within a pair of single quotes
String literals
It is a sequence of characters enclosed between double quotes
Punctuators
1 Parentheses ( )
2 Braces { }
3 Brackets [ ]
4 Semicolon ;
5 Colon :
6 Comma ,
Data Types
Data type specifies the size and type of values that can be stored.
Data types are primarily divided into two categories:
1. Value type
2. Reference type
The categorization is based on following characteristics:
Where they are stored in the main memory
How they behave in the context of assignment statement
1. Value Types:
These data types are of fixed length and stored in the stack.
When the value of a variable is assigned to another
variable, the value is copied.
This means that the two variables will have identical
copies of the value, but stored in two different
memory locations.
Changes done to the one variable does not change the
value of another variable.
The scope of the variable is limited to a
corresponding block where they are defined.
The predefined and simple value types are – int, char,
float, double, bool
The user defined value types are – struct, enum
2. Reference Types
These data types are of variable length and stored in the heap
When the value of a variable is assigned to another variable, the
value is not copied, instead the reference (memory address) of
the variable is copied
The two variables will point (refer) to same memory location.
Changes done to the one variable will change the value of
another variable.
Scope remains until .NET Garbage Collector destroys them
The predefined and simple reference types – objects and strings
User defined reference types – classes, delegates, interfaces, arrays.
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 8
Constants
The variables whose values do not change during the execution of a program are known as
constants.
Constants are defined using the const keyword. Syntax for defining a constant is
Type Values
Bool True, False
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 9
Example:
Flow Control
Testing a condition is inevitable in programming. We will often face situations where we need to
test conditions (whether it is true or false) to control the flow of program.
if..else statement
switch statement
do while and while loop
for loop
foreach loop
C# if statement
C# if-then statement will execute a block of code if the given condition is true.
The syntax of if-then statement in C# is:
if (boolean-expression)
{
// statements executed if boolean- expression is true
}
C# if...else Statement
• The if statement in C# may have an optional else statement. The block of code inside the else
statement will be executed if the expression is evaluated to false.
• The syntax of if...else statement in C# is:
if (boolean-expression)
{
// statements executed if boolean- expression is true
}
else
{
// statements executed if boolean- expression is false
}
C# if-else-if ladder Statement
if(condition1)
{
//code to be executed if condition1 is true
}
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 10
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
...
else
{
//code to be executed if all the above conditions are false
}
C# Switch Statements
The C# switch statement executes one statement from multiple conditions.
C#.switch(expression)
{
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
//code to be executed if all cases are not matched
break;
}
C# do-while Loop
• It is executed at least once because condition is checked at the end of the loop.
Synatx
do{
//code to be executed
}while(condition);
C# while Loop
• In C#, while loop is used to iterate a part of the program several times. If the number of iteration is
not fixed, it is recommended to use while loop than for loop.
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 11
Syntax:
while(condition)
{
//code to be executed
}
C# for Loop
• The C# for loop is used to iterate a part of the program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or do-while loops.
• The C# for loop is same as C/C++.
• Syntax:
for(initialization; condition; incr/decr)
{
//code to be executed
}
C# foreach Loop
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 12
Inheritance: It is a concept used to build new classes using existing classes. Original class is
called Base class and Modified class is called Derived class.
Polymorphism: It is the ability to take more than one form. It is extensively used while
implementing inheritance.
Defining a class
A class is a user-defined data type with a template that serves to define its properties.
A class also defines a state and behaviour of basic programming components called objects.
After class definition we can start creating the variables of that type using declarations.
The basic form of class definition is shown below:
class classname
{
[ variable declarations;]
[ methods declarations;]
class classname
{
type variable1;
type variable2;
.
.
.
type methodname1(parameter list)
{
}
type methodname2(parameter list)
{
}
}
class is a keyword and classname is any valid c#
identifier.
Everything inside the square brackets is optional
class Empty
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 13
Adding a variable
Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called instance variables because they are created whenever an object of the
class is instantiated.
Example:
class Rectangle
{
Adding Methods
• A class with only data fields and without methods that operate on that data has no life.
• The object created by such class cannot respond to any messages.
• Methods are declared inside the body of the class usually after the declaration of instance variables.
• General form of method declaration
type methodname (parameter-list)
// method-body;
• The body describes the operation to be performed on the data. Example of Rectangle class and add
a method GetData() to it.
class Rectangle
{
int length;
int width;
public void GetData(int x, int y)
{
length=x;
width=y;
}
}
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 14
Member Access Modifiers
1. Public
2. Private
3. Protected
4. Internal
5. Protected internal
Creating Objects
• An object in C# is essentially a block of memory that contains space to store all the instance
variables.
• Creating an object is also referred as instantiating an object. (Object is an instance of class)
• Objects in c# are created using a new operator. The new operator creates an object of the specified
class and returns a reference to that object.
Example:
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 15
• The object rect1 does not contain the value for the Rectangle object ; it contains only the reference
(i.e address) to the object.
All the variables must be assigned before they are used. Since we are outside the class, we must use
the concerned object and the dot operator as shown below.
objectname.variable name;
objectname.methodname(parameter-list);
Here the objectname is the name of the object, variablename is the name of the instance variable
inside the object that we wish to access.
methodname is the method that we wish to call and parameter-list is a comma separated list of
'actual values' that must match in type and number with the parameter list of a methodname
declared in the class.
• Example:
One declares variables= instance variables and the other declares methods= instance methods.
Everytime the class is instantiated, a new copy of each is created which are accessed using the
objects (with . operator).
static members and static methods are declared by using a keyword static.
static variable are associated with the class itself rather than with individual objects.
static variables and static methods are referred as class variables and class methods.
static variables are used when we want to have a variable common to all instances of a class.
static methods can be called without using the objects.
Example:
static int max; //static variable
static int add(int x, int y)
{
//your custom code
}
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 16
Constructors
• In c#, Constructor is a method which will invoke automatically whenever an instance of class or
struct is created.
• The constructor will have the same name as the class or struct and it is useful to initialize and set
default values for the data members of the new object.
• In case, if we create a class without having any constructor, then the compiler will automatically
create a one default constructor for that class. So, there is always one constructor that will exist in
every class.
• Syntax:
public class User
{
// Constructor
public User()
{
// Your Custom Code
}
}
• Initialization of all objects can be done by two approaches.
• First Approach uses the dot operator to access the instance variables and then assigns value to
them individually.
• Second approach takes the help of a function like GetData to initialize each object.
Constructor Types
• Default Constructor
• Parameterized Constructor
• Copy Constructor
• Static Constructor
• Private Constructor
Default Constructor
In c#, if we create a constructor without having any parameters, then we will call it as default
constructor and every instance of the class will be initialized without any parameter values.
The drawback of a default constructor is that every instance of the class will be initialized to the
same values and it is not possible to initialize each instance of the class with different values.
Parameterized Constructor
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 17
Copy Constructor
The constructor which creates an object by copying variables from another object is called a copy
constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing
instance.
Static Constructor
When a constructor is created using a static keyword, it will be invoked only once for all of the
instances of the class and it is invoked during the creation of the first instance of the class or
the first reference to a static member in the class.
A static constructor is used to initialize static fields of the class and to write the code that needs
to be executed only once.
Private Constructor
When a constructor is created with a private specifier, it is not possible for other classes to derive from this
class, neither is it possible to create an instance of this class. They are usually used in classes that contain
static members only.
class User
{
// Private Constructor
private User()
{
// Your Custom Code
}
}
Destructor:
• Destructor is a special method of a class and it is used in a class to destroy the object or instances of
classes. The destructor in c# will invoke automatically whenever the class instances become
unreachable.
• In c#, destructors can be used only in classes and a class can contain only one destructor.
• The destructor in class can be represented by using tilde (~) operator
• The destructor in c# won‟t accept any parameters and access modifiers.
• The destructor will invoke automatically, whenever an instance of a class is no longer
needed.
• The destructor automatically invoked by garbage collector whenever the class objects that
are no longer needed in the application
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 18
Destructor Syntax
class User
{
// Destructor
~User()
{
// your code
}
}
Method Overloading
Method Overloading means defining multiple methods with the same name but with different
parameters.
By using Method Overloading, we can perform different tasks with the same method name by
passing different parameters.
Method Overloading is also called as compile time polymorphism or early binding.
Method Overriding
Method Overriding means override a base class method in the derived class by creating a method
with the same name and signatures to perform a different task.
The Method Overriding in c# can be achieved by using override & virtual keywords along with
the inheritance principle.
this keyword
• this keyword is used to refer the current instance of class and by using this keyword we can pass
current instance of the class as a parameter to the other methods.
In case, if the class contains parameters and variables with the same name, then this
keyword is useful to distinguish between the parameters and variables.
NOTE: To demonstrate constructors and its types, method overloading, static members refer
the programs discussed in the class.
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 19