0% found this document useful (0 votes)
35 views19 pages

UNIT 2 - C# Notes

Unit 2 covers the basics of C# programming, including tokens, data types, variables, operators, and flow control statements. Key topics include the definition and use of tokens, various types of operators (arithmetic, relational, logical), and control structures like if-else statements and loops. The document also explains variable declaration, data types, constants, and type conversion methods in C#.

Uploaded by

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

UNIT 2 - C# Notes

Unit 2 covers the basics of C# programming, including tokens, data types, variables, operators, and flow control statements. Key topics include the definition and use of tokens, various types of operators (arithmetic, relational, logical), and control structures like if-else statements and loops. The document also explains variable declaration, data types, constants, and type conversion methods in C#.

Uploaded by

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

UNIT 2 C# Basics

Topics

• Tokens  Classes and Objects


• Data Types  Methods
• Variables & Constants  Access modifiers
• Operators in C#  Static members of the class
• Flow Control and Conditional Statements  Constructors, Destructors, Method overloading

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

 Identifiers are programmer design tokens.


 They are used for naming classes, methods, variables, namespaces, interfaces etc.
C# identifiers enforce following rules:
 They can have alphabets, digits, and underscore characters
 They must not begin with digit
 They are case sensitive, that is, uppercase and lowercase alphabets are distinct
 Keywords in standalone mode cannot be used as identifiers
 C# permits the use of keywords as identifiers when they are prefixed with the @ character

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

C# provides all the basic arithmetic operators


The operators +, -, *, /, and % work the same way as they do in other programming languages
These can operate on any built-in numeric data type
Cannot be used for Boolean data types
Arithmetic operators are used as shown below :
a+b
a-b
a*b
a/b
a%b
Here a and b are known as operands, they may be variables or constants.

KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 2
Following are the arithmetic operators

Operator Meaning Example (a=12, b=5)


+ Addition a + b = 17
- Subtraction a–b=7
* Multiplication a * b = 60
/ Division a/b=2
% Modulo division a%b=2
Relational 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 AND

Bitwise Logical OR

Bitwise Logical Exclusive OR

Truth Tables

KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 3
Assignment Operators

Assignment operator is used to assign a “value” or “value of an expression” to a variable.


The symbol of assignment operator is =
Syntax:
var = value;
Or
var = arithmetic_expression;
Shorthand 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

Statements with simple Statements with shorthand


assignment operator assignment operator
a=a+1 a += 1
a=a – 1 a=-1
a = a * (n+1) a *= (n+1)
a = a / (n+1) a/=(n+1)
a=a%b a %= b

Increment and Decrement operators


• Increment and decrement operators are unary in nature, that is, they operate on one operand
• Increment (++)
• Decrement (--)
• The operator ++ adds 1 to the operand while -- subtracts 1.
• They are used in two forms, namely prefix form and postfix form

Form Meaning

var++ (post increment) Use the value of the variable and increment by ‘1’ for later use

++var(pre increment) Increment the value of variable by ‘1’ and 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

Operator Precedence and Associativity


The precedence is used to determine how an expression involving more than one operator is
evaluated.
There are distinct levels of precedence.
The operators at higher level of precedence are evaluated first.
The operators of the same precedence are evaluated either from “left to right” or from “right to left”
depending on the level is known as associativity property.

KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 5
Literals

 Literals are value constants assigned to


variable‟s or results of an expression in a
program.
 C# supports several types of 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

Example: „A‟, „5‟, „;‟

 String literals
 It is a sequence of characters enclosed between double quotes

Example: “Hello C# .NET”, “2022”, “NEP 2020”

Punctuators

Punctuators are symbols used to group or separate code


They define the shape and function of a program

1 Parentheses ( )
2 Braces { }
3 Brackets [ ]
4 Semicolon ;
5 Colon :
6 Comma ,

Variables and Data Types


Variables

A variable is an identifier that denotes a storage location to store a data value.


Variable may take different values at different times during the program execution.
All the rules of naming an identifier holds good for naming a variable.
Every variable is associated with a data type.
General form of variable declaration is shown below:
type var1, var2, var3,.....varn;
• Variables are separated by commas.
int i, j;
double d;
float f; char ch;
KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 7
• We can also provide values while declaring the variables as given below:
int i=2,j=4; //declaring 2 variable of integer type
char ch='Z';

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

const <data_type> <constant_name> value;


• Example:
• const float PI = 3.142;
• const int m= 3;
const int n=m*5;
• another example:
• int m=10;// non-const value
• const int n= m* 5; // error

Type Values
Bool True, False

String To Integer Conversion


int.Parse()
 Coverts string to integer
 Cannot handle null values
Example:
 string str = “123”; int i = int.Parse(str);
 int n = int.Parse(Console.ReadLine());
Convert.ToInt32( )

 Coverts string to integer


 Handle null values.

KLS Gogte BCA – Belagavi Sem III- C# and .NET Framework -UNIT 2
Page 9
Example:

1 string str = “456”;


int i = Convert.ToInt(str);
2 string str = null;
int i = Convert.ToInt32(str); // null value is converted to 0 (zero)
3 int n = Convert.ToInt32(Console.ReadLine());

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

• It is similar to the for statement but implemented differently.


• It enables us to iterate the elements in arrays and collection classes such as List & Hashtable.
Syntax
foreach(type variable in expression)
{
//body of the loop
}
• The type and variable declare the iteration variable.
• The expression must be an array or collection type and an explicit conversion must exist from the
element type of the collection to the type of the iteration variable.

Concept of Class and Objects:

 C# is a true object-oriented language and therefore underlying structure of all C# programs is


classes.
 C# programs are encapsulated in a class which defines the state and behavior of the basic program
components known as Objects.
 Classes create objects and objects use methods to communicate between them.
 Data items = fields and Functions = methods.

• Three core principles:

Encapsulation - Provides the ability to hide all


internal details of an object from its users. It is
implemented using the access specifiers public,
private and protected.

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

//empty class is also a definition.

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
{

int length; // instance variable


int width; // instance variable
}
• The class Rectangle contains two integer type instance variables. Instance variable are also known
as member variables

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

 One of the goals of object-oriented programming is “Data-Hiding”.


 it is used to control the visibility to outside the class.
 C# Access modifiers or specifiers are the keywords that are used to specify accessibility or scope of
variables and functions in the C# application.

C# provides five types of


access specifiers.

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:

Rectangle rect1; // declare


rect1 = new Rectangle(); // instantiate OR
Rectangle rect1 = new Rectangle();
Rectangl rect2=rect1;

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.

• The method Rectangle() is a default constructor of the class

Accessing Class members:

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:

Rectangle rect1=new Rectangle( );

Rectangle rect2= new Rectangle();


rect1.length = 15; rect2.length =20
rect1.width = 10; rect2.width = 12

Static Members of Classes

 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

 A constructor with at least one parameter is called a parameterized constructor.


 The advantage of a parameterized constructor is that you can initialize each instance of the class
with a different value.

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.

C# Private Constructor Syntax

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.

• The properties of destructor in c# programming language.

• 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

You might also like