wa
Chapter 2
The C# Language
=== —
2.1 Comments
22 Variables and Data Types
2.3 Variable Operations
2.4 Conditional Logic
25 Loops
2.6 Methods
2.7 Questions
Comments can be used to document what the program does and what specific blocks or lines of
code do, Since the C# compiler ignores comments, you can include them anywhere in a program
without affecting your code.
How to Comment?
preceded by an double forward slash.
“is simply ignored by the compiler.
The code of line after the double forward
_ Acomment isii ee
variables
Declaration of variables in c#
syntax
“edaiztype>
Example:
intage;
avariable age of type int (integer) is declared and it can only store integer values.
‘We can assign a value to the variable later in our program like such:
int 298%
age = 24:
However, the variable can also be initialized to some value during declaration. For exampl
int age = 24; =a]
Here, a variable age of type int is declared and initialized to 24 at the same time.
Since, it’s a variable, we ean change the value of variables as well. For example,
intage = 24; |
age= 35;
Here, the value of age is changed to 35 from 24.
fariables in C# must be declared before they can be used. This means, the name and type of
je must be known before they can be assigned a value. This is why C# is callled a statically-
Janguage
Once declared, the datatype of a variable can not be changed within a scope. A scope can be
lock of code where the variable is visible or available to use. If you don’t understand the
ment, don’t worry we'll learn about scopes in the later chapters.
-remember,we can not do the following in C#:
ly typed variables: Alternatively in Ci, we can declare a variable without knowing
e using var keyword. Such variables are called implicitly typed local variables.
¢ declared using var keyword must be initialized at the time of declaration.
determines the type of variable from the value that is assigned to the variable,
example, value is of type int. This is equivalent to:———————————— eer
‘There are certain rules we need to follow Whily
riable in C# are:
nd lowercase), und
> Rules for Naming Variables in Cf
naming a variable. The rules for naming 2 val
1. The variable name can contain letters (upperease
only.
2. The variable name must start with either letter,
For —————————i‘éCsS
"Rules for naming variables in Cit
lerscore (_) and digits
underscore or @ symbol.
Name Valid
subject 01 Valid.
age Valid (Best practice for naming private member variables)
@break Valid (Used ifname is a reserved keyword)
101 subject Invalid (Starts with digit)
‘your_name Valid
Invalid (Contains whitespace)
your name
3, Ciis case sensitive, It means age and Age refers to 2 di
4. Avvariable name must not be a C# keyword. For examp!
name:
C# Primitive Data Types
1, Boolean (bool)
© Boolean data type has two possible values: true or false
> Default value: false
Boolean variables are generally used to check conditions such as in if statements, loops, etc.
fferent variables.
le, if, for, using can not be a variableSn
2, Signed Integral
These data types hold integer va a ; ‘table bi
ane bt is ased fr sig. lues (both positive and negative). Out of the total available bils,
21 sbyte
Size: 8 bits
Range: -128 to 127
Default value: 0
For example:
using System;
namespace DataType
class SByteExample
{
public static void Main(stringf| args)
{
sbyle level = 23;
Console. WriteLine(le vel);
pe: ~32,768 t0 32,767
mult value: 023° int
Size: 32 bits
Range: -231 to 231-1
Default value: 0
For example:
Using System;
Namespace Datatype
{
class IntExampie
{
public static void Mein(string[] args)
{
int score = 51092;
Console.WriteLine(score);
}
}
‘Output; $1092
2.4 long
Size: 64 bits
‘Range: —263 to 263-1
Default value: OL [Lat the end represem the value is of long type]
For example:
using System;
namespace DataType
{
Class LongExample
{
public static void Main(string{] args)
{
long range = -7091821871L;
Console. Write ine(range);
}
Output: ~7091821871eee
3 Unsigned Integral
‘These data types only hold values equal to or types
. , Breater than 0. We calls these data to
tore values When We are stire, We Won"t have negative values. eee
3.1 byte
Size: 8 bits
Range: 0 to 255
Default valu
namespace Datatype
dass ByteExample
{
pubiic static void Main(string) args)
{
byte age = 62;
Console. WriteLine (level);
l
‘Output: 62 -
3.2 ushort
Size: 16 bits
Range: 0 to 65,535
Default value: 0)
For example:
using System: _
namespace DataType
{
class UShortExampie
{
| public static void Main(stringf] args)
{
ushort value = 42019;
Console, WriteLine(value);3.3 uint
Size: 32 bits
Range: 0 to 232-1
Default value: 0
For example:
using System;
namespace DataType
{
class UIntExample
{
public static void Main(stringl] ar08)
{
uint totalScore = 1151092;
Console. WriteLine(total Score);
‘Output: 1151092
3.4 ulong
Size: 64 bits
Range: 0 to 264-1
Default value: 0
For example?
using System;
namespace DataType
{
class ULongExample
{
public static void Main(stringl] args)
{
ulong range = 17091821871L;
Console.WriteLina(range);
}
Output: 17091821871CS eT
4. fosting Point
data types hold floating point vatues ie,
1236 92.17, etc.
‘41 Bloat
Single-precision floating point type
Sizer 32 bits
Range: 1.5 * 10-45 to 3.4 x 103%
Default value: 0.0F [F at the end represent the value is of float type]
For example:
numbers containing decimal values. For example,
class FloatExample
{
public static void Main(stringf] args)
{
float number = 43.27F;
Console. Writel ine{number);
Output: 43.27
42 double
Double-precision floating point type.
Size: 64 bits
Range: 5.0 « 10-324 to 1.7 x 10308
Default value; 0.0D [D at the end represent the value is of double type]
For example:
using System;
namespace DataType
{
dass DoubleExample
{
public static void Main(stringl] args)
{
double value = -11092.53D;
Console. WriteLine (value);
}
}
)
Output: -11092.535. Character (char)
D> Ttrepresents a 16°bit unicode character
Size: 16 bits
Default value: ‘\0"
Range: U +0000 ('\u0000") to U + FFFF (uff?)
For example:
using System;
namespace DataType
{
class CharExample
{
public static void Main(string{] args)
{
char cht ="u0042;
char ch2
Output: B
x
The unicode value of *B’ is *\u0042", hence printing ch! will print ‘BY.
6. Decimal
> Decimal type has more precision and a smaller range as compared to floating point
(double and float). So it is appropriate for monetary calculations.
Size: 128 bits
Default value: 0.0M [M at the end represent the value is of decimal type]
Range: (-7.9 « 1028 to 7.9 * 1028)/(100 to 28)
For example:
using System;
namespace DataType
{
class DecimalExample
{
public static void Main(string[] args)
{
decimal bankBalance = §3005.25M;Console. Write ine(baikBalanca)
}
}
‘Ontput: $3005.25
co# Literals
Let’s look at the following statement;
ist number = 41;
Here,
3 int is. a data type
number is 2 variable and
2 Alisa literal
Literals are fixed values that appear in the program, They do not require any computation. For
example, 5, false, “w" are literals that appear in a program directly without any computation.
2 Boolean Literals:
true and false are the available boolean literals,
hey are used to initialize boolean variables.
For example:
bool isValid = true:
bool isPresent = false:
> Integer Literals:
% Integer literals are used to initialize variables of integer data types ive., sbyte, short, int,
long, byte, ushort, uint and ulong.
+ [fan ititeger literal ends with L or I, itis of type long. For best practice use L (not 1),
long value! = 4200910L;
long value2 = -10928190L;
+ fan integer literal starts with a Ox, it represents hexadecimal value. Number with no
prefixes are treated as decimal value. Octal and binary representation are not allowed in
Ce.
int decimalValue = 25;
int hexValue = Ox11c;// decimal value 284
2 Floating Point Literals:
4% Floating point literals are used to initialize variables of float and double data types.
4 Ifa floating point literal ends with a suffix f or F, itis of type float, Similarly, if it ends
with d or D, it is of type double, If neither of the suffix is presemt, it is of type double
by default.
% These literals contains ¢ or E when expressed in scientific notation.double number = 24.67;// double by default
float value = -12.29F;
double scientiicNotation = 6.21e2:/ equivalent to 6:21 x 102ie., 621
> Character and String Literals:
Character literals are used to initialize variables of char data types:
Character literals are enclosed in single quotes, For example, “x’, ‘p’, ete.
They can be represented as character, hexadecimal escape sequence, unicode representation
or integral values casted to char.
[ear cht = "Ry character
char ch2 = "\0072'/! hexadecimal
char ch3 = \u0059"y/ unicode
char ch4 = (char)107¥// casted from integer
String literals are the collection of character literals
® They are enclosed in double quotes. For example, “Hello”, “Easy Programming”, etc.
string firstName = "Kiran*;
string lastName = *Gurbani";
C# also supports escape sequence characters such as:
[Character “Meaning
Single quote
Double quote
Backslash.
\n Newline
\r Carriage return
\t Horizontal Tab
\a Alert
tb Backspace
that tells the compiler to perform speci fic mathematical or logical)
1d provides the following type of operators
‘An operator is a symbol
manipulations. C# has rich set of built-in operators ant
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5, Assignment Operators
6. Mise Operators(eS
L Arithmetic Operators
‘ollowing table shows all the arithmeti i
- ete B holds 20 then” tthmietic operators supported by C#, Assume variable A holds 10
Show Examples
=
Adds two operands
z Sulbstracts second operand from the first
ea both operands A*B=200
r Divides numerator by de-numerator B/A=2
* Modulus Operator and remainder of after an integer division B%A=0
er Increment operator increases integer value by one AH = 11
= Decrement operator decreases integer value by one Av=9
9, Relational Operators
Following table shows all the relational operators supported by C#. Assume variable A holds 10
and variable B holds 20, then ~
Show Examples
Description e
Checks if the values of two operands are equal or not, if'yesthen | (A = B) is not true
condi
: Checks (A!=B) is true.
not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of right | (A > B) is not true.
operand, if yes then condition becomes true.
< Cheeks if the value of left operand is less than the value of right (A = B) is not true.
value of right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value | (A <= B) is true.
of right operand, if yes then condition becomes true,
3. Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds
Boolean value truc and variable B holds Boolean value false, then —condition becomes true.
Called Logical OR Operator. If'any of the two operands is non zero (A |) B) is true.
then condition becomes true.
1(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,
4. Bitwise Operators
Bitwise operator works on bits and
are as follows —
perform bit by bit operation. ‘The truth tables for &, |, and
‘Assume if A=60; and B = 13; then in the binary format they are as follows
A=0011 1100
B=0000 1101
A&B = 0000 1100
AJB = 0011 1101
A‘B = 0011 0001
~A=11000011
The Bitwise operators supported by C# are listed in the foll
60 and variable B holds 13, then —
Show Examples
=
lowing table. Assume variable A holds
inary AND Operator copies a bit to the result ifit
(A & B) = 12, which is 0000 1100
exists in both operands.
I Binary OR Operator copies a bit if it exists in (A|B)=61, which is 0011 1101
either operand,
ee Binary XOR Operator copies the bit if it is set in (A* B) = 49, which is 0011 0001
‘one operand but not both.inary Ones Complement Opera 1
has the effect of “fipping’ bite SMAY and
(-A)= 61, which is 1100 0011
complement due to a signed binary
number.
Binary Left Shift Operator,
The lei
is moved left by the number of eas alte
+ of bits specified by
A <<2= 240, which is 1111 0000
‘There are following assignment operators supported by C# —
Show Examples
Simple assignment operator, Assigns values from right
side operands to left side operand
Add AND assignment operator, Itadds Tight operand to
the left operand and assign the result to left operand
the right operand,
Binary Right Shift Operator. The
= + The left operands = ae
value is moved right by the number of bis slieaieipaiaiass
specified by the right operand,
5, Assignment Operators
__ Example
C= A+B assigns value of A +
B into
C += A is equivalent toC =C +
Subtract AND assignment operator, t subtracts right
operand from the left operand and assign the result to
left operand
is equivalent to C = C -
Multiply AND assignment operator, It multiplies right
operand with the left operand and assign the result to
left operand
C *=A is equivalent toC =C*
A
Divide AND assignment operator, It divides left
operand with the right operand and assign the result to
left operand
C/=A is equivalent toC=C/ A
Modulus AND assignment operator, It takes modulus
using two operands and assign the result to left operand
=
‘Yr A is equivalent to C=C
A
<= Left shift AND assignment operator C <<=2 issameas C=C<<2
ae Right shift AND assignment operator C>>=2issameasC=C>>2
& Bitwise AND assignment operator C & 2issameasC=C &2
a Bitwise exclusive OR and assignment operator C*%=2 is same as C= C2
F Bitwise inclusive OR and assignment operator C{=2issameasC=C|2
6. Miscellaneous Operators
There are few other important operators including sizeof, typeof and ?:supported by C#.= Description
Returns the size of a data type.
sizeoitint), returns 4.
typeof StreamReader);
Returns the type of a class.
Returns the address of an variable. ‘a; returns actual address of the variable,
e Pointer to a variable ‘a; creates pointer named ‘a’ to a
variable.
% ‘Conditional Expression If Condition is true ? Then value X:
Otherwise value ¥
If (Ford is Car) // checks if Ford is an
object of the Car class.
‘Determines whether an object is of a certain
type.
as Cast without raising an exception ifthe cast | Object obj = new SiringReader(“Hello”);
fails. StringReader r= obj as StringReader;
Operator Precedence in C#
n expression. This affects evaluation
Operator precedence determines the grouping of terms in a
hers; for example, the multiplication
of an expression. Certain operators have higher precedence than ot!
‘operator has higher precedence than the addition operator.
For exemple x = 7 +3 * 2; here, x is assigned 13, not 20 because operalor * has higher
precedence than +, so the first evaluation takes place for 3*2 and then 7 is added into it
Here, operators with the highest precedence appear at the top of the table, those with the lowes,
appear atthe bottom. Within an expression, higher precedence operators are evaluated first.
Show Examples
Left to right
Unary 4-1 ~44-- (type)? & sizeof Right to teft |
Multiplicative *i% Left to right |
Additive #5 Left to right |
Shift <<>> Left to right |
Relational <>= Left to right
Equality ' Left to right | |
Bitwise AND. & Left to right
Bitwise XOR a Left to right |
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR _| il “ [eft to rightConditional
Right to left
Ia tnr— com dys hm f= | Rightto lef
Sto=0
‘A-statement that can be executed
: b ot
atement is often a block of code ased on a condition is known as a “Conditional Statement”.
The following are the 2 types;
1. Cobditional Branching
2, | Conditional Looping
4, Conditional Branching
is statement allow: cl
This S you to branch your code depending on whether or not a certain condition is
In C# are the following 2 conditional branching statements:
1. IF statement
4, Switch statement
IF Statement
‘The if statement allows you to test whether or not a specific condition is met.
syntax
if()
;
Else if()
-;
Else:
-;
oP he pos
Example
Write a Program to find the greatest number using an if statement
4, using System:
2 clags ildemo
af
4, public static void Main()
5 f
6 inta,b:7. Console. WriteLine(“enter 2 no "}
|. a=int Parse (Console Readline()) |
9. _ b=Int Parse(Console ReadLine()): |
10. if(a>t)
4
42, Console WrteLinet“e is greater’)
3
14, else If(a<'b)
45. {
46. Console WriteLina(’b is greather);
47. }
18. else
19. {
20. Console: WeiteLineboth ave Equals”);
2}
22, Console, ReedLine():
123, 3
Switch Statement
The switch statement compares two logical ex]
‘Syntax
Swilth()
{
Case :
Break;
pressions.
Default:
. Break;
) ageneeace
23 %e sees one
u
Note: In the case of the C# Language, using a break after every case block is mandatory, even’
the default.i Le)
exariple
SBR
Write @ Program to choose & color sing a swi
tch case,
‘ing System;
using System Collections. Generic;
using System. Ling;
using System.Text;
using System. Threading Tasks:
namespace ConditionalStatementDemo.
{
class Switchdemo
{
int ch;
Public void getdata()
{
‘Console. WriteLine(“choose the following coli);
‘ch = int Parse(Console,ReadLina());
‘switch (ch)
{
case 1:
Console WriteLine¢"you choose Red");
break;
case 2
Console. WriteL ine(*you choose Green");
break;
case 3:
Console.WriteLine("you choose Pink");
break;
default
Console Writél ine(*you cant choose cortect eblor');
break;
}
public static void Main()
{
‘Switchdemo obj = new Switchdemo\);
obj.gatdata();
Console. ReadLine()|
Conditional Loops
C# provides 4 loops that allow you to execute @ bl
is met; they are:
> For Loop
3 While Loop:
2 Do... While Loop
2 Foreach Loop
Jock of code repeatedly until a certain condition
Each and every loop requires the following 3 things in common:
4. Initialization: That sets a starting point of the loop.
2. Condition: That sets an ending point of the loop.
3, Iteration: That provides each level, either in the
forward or backward direction.
Direction
Syntax
1. For(initializar;Conition;{terator)
2 {
3.
4}
Example
4. using System;
2. _ using System.Collections.Generic,
3. using System.Ling:
4, using System.Text;
5. using System. Threading.Tasks,
6.
7.
8.
namespace ConditionalStatementDemo
sf
o class FotLoop
10 {
1.
12. Public void getdata()a its
50; 144)
Console. WriteLine(iy
}
}
public static void Main()
{
a ForLoop # = new Fort oop();
f.getdata();
Console. Read ine();
7, While(Condition)
mint
3,
4)
Example
4, using System;
2. using System. Collections. Generic:
3, using System.Ling;
4, _using System.Text;
5, using System: Threading. Tasks;
6
7.
8
9.
namespace ConditionalStatementDemo
Class WhileDemo
AC ib
M1. int x
12. public void whiledemo()
13, {
14, while (x <= $0)
rs {
16. Console. Writeline(x);Do...
}
‘
public static void Main()
{
\Whiebemo obj = new WhileDemo(
obj whiledemo();
Console.ReadLinet);
. While Loop
‘Syntax
1.
a
3.
4.
3
pee
‘Do
{
< statement >
}
While(Condition)
i
using System;
using System.Collections,Generic;
using System.Ling;
using System.Text;
using System. Threading Tasks;
namespace ConditionalStatementDemo
{
class DoWtileDemo
{
int x;
public void does()
do
{
Console WriteLine(x);
att;
}while (x <= 50);
public static void Maing)
{
DoWhieDeme obj = new DoWhileDemoy);
‘Gbj.does();
Console. ReadLine();
In the-case of a for and a while loop from the fist exeeution there will be condition verification.
But in the case of 4 do .. while, the condition is verified only after the first execution, soa
rinimam umber of executions occur. In the case of far and while the’ minimurs number of
executions will be zero whereas it is | in the case of a do-while loap.
Foreach Loop
Itis specially designed for accessing the values of an array and collection.
Syntax
Foreach(type var in col/Arr)
1
24
3, statement >;
4.
Amethod is a code block that contains a series of statements.
A program causes the statements to be executed by calling the method and specifying any
required method arguments,
In C#, every executed instruction is performed in the context of a method.
‘The Main method is the entry point for every C# application and it is called by the common
language runtime (CLR) when the program is started.
Method Signatures
Methods are declared in a class or struct by specifying the access level such as public or private,
optional modifiers such as abstract or sealed, the zeturn value, the name ofthe method, and any
method parameters. These parts together arc the signature of the method.]ed by commas. Empty parenthesey
hree methods:!
ses and are separati
___ Method parameters are enclosed in parenth
indicate that the method requires no parameters:
abstract class Motorcycle
{
This class contains
I Anyone can call this
public void StartEnginel) (* Method statements here ry :
Il Only derived classes can call this
protected void AddGas(int gallons) { * Method
JI Derived classes can override the base class implementation.
public vitual int Drive(int miles, int speed) { * Method statements here */ return 1; }
1 Derived classes must implement this.
public abstract double GetTonSpeed();
statements here “/ }
Method Access
Calling a method on an object is like accessing @ field. After the object name, add a period, the
name of the method, and parentheses. Arguments are listed within the parentheses, and are separéted
by commas. The methods of the Motorcycle class can therefore be called as in the following example:
‘class TestMotorcycle: Motorcycle Tl
{
public override double GetTopSpeed() |
|
{
return 108.4;
}
static void Main() |
{
TestMotorcycie moto = new TestMotorcycle();
moto StartEngine();
moto.AddGas(15), |
moto Drive(5, 20);
double speed = moto.GetTopSpeed():
Console. WriteLine("My top speed is (0)", speed);
}
Method Parameters vs. Arguments
i ee definition specifies the names and types of any parameters that are required. When |
calling code calls the method, it provides concrete values called arguments for each parameter, The
|must be compatible with the 5,
Signs oh a ttt eae ay) wee
Meter named defined in the method.
For example:
ponte void Caller()
{
inurumA = 4;
1). Call with an int variable
int product = Square(numA);
int numB = 32;
i Call with another int variable,
int productB = Square(numB);
1) Call with arvintegor literal,
int productC = Square(12);
1) Call with an expression that evaulates to int,
product = Squara(producta * 3):
)
int Square(int i)
{
/ Store input argument in a local variable.
int input =f
retum input * input:
Explain data type in C#?
What is Constant? Explain type of Constants in C#?
‘What is Keyword and list some keyword in C#?
‘What are different Rules for defining variable names?
Expiain syntax of conditional statements if and if-else with suitable example
Explain Different types of Loops with syntax
Explain For loop syntax with suitable example.
Explain while loop syntax with suitable example.
Explain how to declare and Access Methods in C#
yes eee o
oOo