Introduction To C#: Be Programs
Introduction To C#: Be Programs
Chapter-2
INTRODUCTION TO C#
Executable programs are written to carry out certain tasks and require the method Main in one of the classes.
Component libraries do not require a Main declaration because they are not standalone application programs.
They are written for use by other applications.
C# Program
Executable Library
Programs Programs
CLR Application
Output CLR
Output
2, Simple C# Program:
class SampleOne
Class Declaration :The first line class SampleOne declares a class, which is an object orient construct. Classisa
keyword and declares that a new class definition, that specifies the name of the class to be defined.
The braces: C# is a structured language, meaningcode blocks are always enclosed by braces { and ). Therefore
.everyclass definition in C# begins with an opening brace and ends with a corresponding (
closing braces} that
defines a method named Main. Every C# executable program must include the )
Main( method in one of the
classes. This is the staring point for executing the program. A C# applications can have any number of classes but
only one class can have the main method to initialte the execution. This line conaions number of keywords
public,static and void.
public -The keyword public is an access modifier that tels the C# complier that the main method is
accessible by anyone.
Static- the keyword static declares that the Main method is global one and can be called without creating
an instance of the class. The complier stores the address of the method as the entry point and uses this
Void- The keyword void is a type modifier that states that the Main method does not return any value.
The Output Line: the only executable line in the program is
3, Namespaces :Namespaces in C# are used to organize too many classes so that it can be casy to handle the
application. In a simple C# program, we use System.Conso le where System is the namespaceand Console is the
class. To access the class of a namespace, we need to use namespacename.classname. We can use using keyword
so that we don't have to use complete name all the time.
using System;
namespace ConsoleApplicationl
class Program
Console.WriteLine("Hello !");
4Addin Comments:Comments are used for explaining the code and are used in a similar manner as in Java,
C C+t.Compilers ignore the comment entries and do not exccute them. Generally, programming anguages
or
contain two types ofcomments but in C#, there are 3Types of comments:
1. Single Line Comments :It is used to comment a single line. These comment can be written in a
separate line or along with the codes in the same line. But for better understanding always use the
comment in a separate line.
Syntax :
/Single Line Comments
2. Multiline Comments :It is used to comment more than one line. Generally this is used to comment
out an entire block ofcode statements.
Syntax :
* Multiline
Comment */
5. Main Returning Value: Main( ) can also return a value if it is declared as int instead of void. When the
rturn type is int, we must include a return statement at the end of the method.
using System;
namespace ConsoleApplicationl
class Program
{
static int Main(string] args)
6,Using
can
Aliases
be applied
for
only to
Namesnace
the namespaces
Classes
ad
: System
cannot
is a namespace and Console
be applied to the class. This
is a class,
by using
aliases for namespaceclasses. The format is
ZPassing String obiects to WriteLine Method: String values can be stored in string objects and usethese
objects as parameters to the WriteLine method. String data type can be used to create a string variable and
assign a string constant.
string S ="SRC»
The content of S may be printed out using the WriteLine method:
System.Console.WrtieLine(S);
8. Comnmand Line Arguments: There may be an occasion when we may like our program to behave in a
particular way depending on the input provided at the time of execution. This can be done using Command line
arguments. Command line arguments are parameter supply to the main method at the time of invoking it for
must be declared with static modifier. It is the main place where a program starts the execution and end. The Main
method can have a parameter and these parameters are known as zero-indexed command line argument. The
Main method in C# is always declared with static because it can't be called in another method of function. The
Main method instantiates other objects and variables but there is no any method there that can instantiate the main
method in C#. On another hand, the main method doesn't accept parameter from any other function. It only takes
a parameter as an argument via command line argument.
10, Providing interactive Input: Different ways for giving value to the variable are,
System.Console class provides Read, ReadLine and ReadKey methods to read user inputs.
System.Console.readLine);
11, Using Mathematical Eunctions: The System.Math class in C# provides methods are properties to
mathematical operations, trigonometric, logarithmic calculations, etc. The C# Math class has many
perform
methods that allows you to perform mathematical tasks on numbers.
method can be used to find the highest value ofx and y:
O Math.Max(x,y): The Math. Max(x,y)
Console. WriteLine(Math.Sqrt(64);
The will not allow to run the program until all the errors are removed from
thrown by the compiler. compiler
will generate the executable
the program. When all the errors are removed from the program, then the compiler
file.
int a, b:
U Semantic errors :The semantic errors exist when the statements are not meaningful to the
compiler.Forexample,
atb=c;
13, Program Structure :An executing C# progr am may contain a nunber coding blocks as shown in
below:
Document Section
Optional
Optional
Interfaces Section
Classes Section
Optiona
Optiona
Essential
0 Documentation section: consists of a set of comments giving the name of the program, the author, ate
and other details, which the programmer may like to use at a later stage.
O Using directive section: will include all those name spaces contain classes required by the application.
This section tells the compiler to look in the namespace specified for these unresolved ciasses.
D Interfaces section :
is similar to a class but contains only abstract members. Interfaces are used when we
want to implement the concept of multiple inheritance in a program.
O Classes section: A C# program may contain multiple class definitions. Classes are the primary and
essential elements of a program. These classes are used to map the objects of real world problems. The
number of classes depends on the complexity ofthe program.
D Main method section :It is the essential part of the program.A program may contain onty this part. The
main method creates objects of various classes and establishes communication between them. On reaching
the end of the main the program terminates and the control passes back to the operating system.
JVM this is not compiled on run time execution of the JVM to construct meaningfu!
and relies
assembly code. C# produced assemblies which are compiled code which then run against the CLR this
represents a streamlining of code execution as there is less emphasis on the underlying virtual machine
to produce executable code.
C# LIterals
Integer Single:
Real' iterals sting Literals
Literals Character
Literals
1. Numeric literals :are divided into Integer literals and real literals.
Integer literals: have two possible forms; decimal and hexadecimal. Decimal integer consists of a
set of digits 0through 9proceeded by an optional minus sign.
123 -321
2. Boolean literals: value are true and false. boolean-literal:true false. The type ofa boolean-literal is bool.
3. Character literais:
A character literal represents a single character, and usually consists of a character in quotes, as
in 'a'.
character-literal:' character
String literals: C# supports two forms of string literals: regular string literals and verbatim string
literals.A regular string literal consists of zero or more characters enclosed in double quotes, as
in "hello", and may include both simple escape sequences (such as\t for the tab character) and
2.Variables; A yariable is a name given to a memory location and all the operations done on the variable
eftects that memory location. In C, all the variables must be declared before they can be used. is the basic
unit of storage in a program. The value stored in a variable can be changed during program execution.
Here, datatypemust be a valid C# data type including char, int, float, double, or any user-defined data type, and
variable list may consist ofone or more identifier names separated by commas. For example,
int i, j, k;
char c, ch;
3,DataTypes:
C# Data Types
Every variable in C# is associated with a data type. Data types specify the size and type of values that can be
stored. C# is language rich in its data types. The variety available allows the programmer to select the type
appropriate to needs of the application. The types in C# are primarily divided into two categories:
Value types
Reference types
Value types and reference types differ in two characteristics:
Where they are stored in memory
How
( they behave in the context of assignment statements
User-defined types are known as complex types or primitive types , which includes Enumeration and
Structures
Reference types:( which are variable length) re stored on the heap, and when an assignment between two
reference variables occurs, only the reference is copied; the actual value is remains in the same memory location.
This means that there are two references toa single value. Reference type is furtber classified as predefined and
user defined types.
• Predefined types are known as simple types or primitive types , which includes Objects and
Strings
User-defined types are known as complex types or primitive types , which includes Classes,
Pointers: The third category of types is called pointers is available for use only in unsafe code. Value types and
reference types are further classified as predefined and user defined types.
Values types (which are of fixed length)are stored on the stack, and when a value of a variable is assigned to
another variable, the value is actually copied. This means that two identical copies of the value are available in
memory. Value type is further classified as predefined and user defined types.
Predefined types are known as simple types or primitive types , which includes Integer, Real numbers,
Structures
Simple Types
Boolean Numeric
Types Character
Types Types
Signed Unsiged
Types Types
1. Boolean Type: is used when a particular condition is tested, during the execution of the program. There are
only two values that a Boolean type can take: true or false. Both have been declared as a keywords. Boolean
type is denoted by the keyword bool and uses only one bit of storage.
2. Numeric type: is divided into three types :
i.
Floating point type :Floating point numbers represent rcal numbers in computing. Real numbers
measure continuous quantities, like weight, height, or specd. In C# we have threc floating point
types: float, double, and decimal.
Type Size
float
4 bytes
double 8 bytes
ii. Integral type: Integral type can hold whole numbers such as 123,
-96 and 5679. The size of the values that can be stored depends on the Integral data type we choose.
C# supports the concept of unsigned types and therefore it supports eight types of integers.
short
ushort uint
int
Signed integers: Signed integer types can hold both positive and negative numbers.
Size Min Value Max value
(Byte)
Sbyte 1 -128 127
Long -9,223,372,036,854,775,sos9,223,372,036,854,775,807
b. Unsigned integers: We can increase the size of the positive value stored in an integer type by making
it unsigncd.
byte 255
Ushort 2 65,535
Uint 4 4,294,967,295
Ulong 18,446,744,073,709,551,615
|O.|0
iüü. Decimal Type: is high precision,128 bit data type that is designed for use in financial and monetary
calculations. It can store values in the range I.0 X I10 -28 to 7.9 X I02% with 28 significant digits.
3. Character types: in order to store single character in memory ,C# provides character data type care called
char. The char type assumes a size oftwo bytes but holds a single character.
4. Reference tynes Unlike value types, a reference type doesn't store its value directly. Instead, it stores the
address where the value is being stored. In other words, a reference type contains a pointer to another memory
location that holds the data.
The following image shows how the system allocates the memory for the above string variable.
RAM
Actualvalue
Reference type variable
contains address where the
value is stored
As you can see in the above image, the system selects a random location in memory (0x803200)for the
variable s. The value ofa variable s is Ox600000,which is the memory address of the actual data value. Thus.
reference type stores the address of the location where the actual value is stored instead of the value itselfThe
String
Arrays (even if their elements are value types)
Class
Delegate
5. Decalration of variables : A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C# bas a specific type, whichdetermines the size and layout ofthe variable's memory
the range of values that can be stored within that memory and the set of operations that can be applied to the
variable. The general form of declaration of
variable is:
type variable1,variable2, variables,.. .variableN;
variables are separated by commas. A declaration statement ends with semicolon.
Example :int count;
float x,y;
6. Initialization of variables: To create a variable, you must specify the type and assign a value:
=
it
Syntax is datatype variable name value:
variable. The right side of the operator is a value that will be assigned to left side variable. Above, 100 is
assigned to a variable num.
7.Defanlt values A variable is either explicitly assigned a value or automatically assigned a default value.
The following categories variables are automatically initialized to their default values:
Static variables
Instance variables
Array elements
The default value of a variable depends on the type of the variable.
8. Constant variables: A variable whose value can not be changed during the execution of the program is
called a constant varjable. In C#, a const keyword is used to declare constant fields.and constant' local. The
value of the constant field is the same throughout the program or other
in words, once the constant field is
assigned the value of this field is not be changed. In C#, constant fields and locals are not variables, a constant
is a number, string, null reference, boolean values. For example :
const int rows=10:
const int num=30;
9. Scone of Variables: The scope of the variable is the region of code within which the variable can be
accessed. This depends on the type of the variable and place of its declaration. C# defines several categories of
variables. They include:
Static variables
Instance variables
Array elements
Value parameters
Reference parameters
Output parameters
Local variables
Static and instance variables at the class level and are known as fields or field variables. The scope
are declared
of these variables begins at of their declaration and ends when the Main method terminates.
the place
The reference and output parameters do not create new storage locations. Instead they represent the same storage
Jocations as the variables that are passed as arguments. The scope of these variables is always the same as the
underlying variables.
Variables declared inside the methods are called local variables. They are not available for use outside the method
definition. Local variables can also be declared inside program blocks that are defined between an opening braces
{and a closing braces ). The scope of the variables starts immediately after its identifier in the declaration and
extends up to the end of the block contining the declaration. Within the scope of the local variable, it is an error
to declare another local variable with the samne name. For example,
class ABC
static int m;
int n;
void fun( int x, ref int y, out int z, int a)
int j=10;
n as instance variable
x as value parameter
o y as reference parameter
it
needs a reference it
finds a value type where its
logical operations.
mathematicaland
An Operator
Operators
logical operations.
are
is
used
OPERATORS AND EXPRESSIONS
a symbol that
in programs
tells the computer to perform certain
Subtraction
multiplication
division
% modulo division
:when both the operands in a single arithmetic expression such as a + bare integers,
i.Integer arithmetic
and the operation is called integer arithmetic. For example: at
the expression is called integer expression
b where a=10 b=15
ii. Real arithmetic :when both the operands in a single arithmetic expression such as a +bare real, the
is called real expression and the operation is called real arithmetic. For example :a+ b where
expression
a=10.4 b=15.7
Mixed mode arithmetic: When one the operand is real and the other is integer, the cxpression
is
iii. of
is converted to real and real arithmetic is performed. The result will be real. Thus 15/10.0 produces the
result 1.5 where as 15/10 produces the result 1
3. Relational onerator: In order to evaluate a comparison between two expressions we can use the relationaland
according to its Boolean result. We may want to compare two expressions, for example, to know if they are equal
Here the relational and equality operators that can be used in C#:
or if one is greater than the other is. is a list of
Equal to
Not equal to
Greater than
Less than
Greater than or equal to
Less than or equal to
Y^VT|:
Here there are some examples:
(7=5) I/ evaluates to false
(3 != 2 ) Il evaluates to true
4. Logical onerator: The operator !is the C# operator to perform the Boolean operation NOT it has only one
operand, located at its right, and the only thing that does is to inverse the value of it, producing false if its
it
operand is true and true if its operand is false. Basically, returns the opposite Boolean value of evaluating its
it
operand. For example :
!(5 =5) Il evaluates to false because the expression at its right (5=$ ) is true.
are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a
&&b:
&& operator
a && b
Thus being false only when both operands are false themselves. Here are the possible results
two operands is true.
ofa || b:
I| operator
a a b
||
true true true
(
Increment and decrement operator : Shortening even more some expressions ,the increase operator
C=c+1;
The three of them increase by one the value ofc.
are all equivalent in its functionality.
probabiy produce different executable code depending
C the three previous expressions
In the early compliers,
on which one was used.
be
be used both as a prefix and as a suffix. That means that
can
it
A characteristic of this operator is that can
it
the variable identifier ( ++a) or after (at+ Although in simple expressions like att or
written either before
).
it
the result of the increase or decrease
+ta both have exactly the same meaning, in other expressions in which
an important difference in thcir meaning.
operation is evaluated as a value in an outer expression they may have
In example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied
a value thatexpression
7. Conditional onerator: The conditional operator evaluates an expression returning if
is true and a different one if the expression is evaluated as false. Its format is :
Condition ? result1 :result2;
is true the expression will return result 1, if it is not will return result2.
condition
it
If
value specified after the question mark was discarded in favor of the second value ( the one after the colon
they store.
Operator Equivalent Description
& AND Bitwise AND
OR Bitwise Inclusive OR
XOR Bitwise Exclusive OR
NOT Unary Complement ( bit inversion )
<< SHL Shift Left
Special Operators
Purpose
is
relational operator
as
relational operator
typeof
type operator
arranged as per the syntax of the language. C#can handle any complex mathematical expressions. Forexample:
res=a*btc;
A= (x+Y)*C;
10. Evaluation of Expressions: Expressions are evaluated using an assignment statement of the form.
variable = expression:
variable is any valid C# variable name. 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. All variablesused in the
11. Precedence of Arithmetic Onerators:_An arithmentic expression without any paraenthisis will be
evaluated from left toright using the rules of the precedence of operators. There are two distinct levels of
arithemetic operators in C#.
priority
pas ,
the high priority operators are applied as they are encountered. During
example,
short b=75;
Traditional C casts are augmented in C++ by a function-call notation as a syntactic alternative. The general form is
type_name (expression);
it
ofa given type to another. There are sevcral ways to do
Type casting Operator allows you to convert a data
this in C#:
int i;
float f= 3.14;
I=( int ) f;
Here, the
number 3. 14to an integer value (3), the remainder is lost.
The previous code converts the float
notation:
same thing in C# is using the functional
). Another way to do the
Type casting Operator was ( int betwecn parantheses :
by the type and enclosing the cexpression
the expression to be converted
preceding
i= int(f);
Both ways of type casting are valid in C #.
DECISION MAKING AND BRANCHING
l Introduction
evaluated
: Decision making
or tested by the program, along with
structures requires the programmer to specify one or more conditions tobe
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.
if
Its is:
if(condition)
statement;
Here condition is an integer expression and statement is an executable statement. The statement will be executed
only if the condition has a nonzero value.Whenever an integer expression is being evaluated as a condition, a
nonzero value is understood to mean true" and a zero value to mean "false". Here is a program that will find
the highest value of the three integers.
using System;
void main()
{
int nl,n2,n3;
What actually happens when this program is run, you entered 34,46 and 78. nl=34, n2=46 and n3=78. First
max is assigned 34. Then, since 46 is greater than 34, max is assigned 46. Finally, since 78 is greater than 46,
max is assigned 78,and that value is displayed. The above code makes use oftwo if statements. You can make
use of as many if statements as you need in a program.
The I-Elsestatement:
else
{
<one or more statements>
}
For example:
if(n-2)
{
System.Console. WriteLine("Even No");
else
else
<one or more
statements>
else
For example:
if(sex is female)
if(balance>5000)
bouns=0.05*balance;
else
bouns=0.02*balance;
}
else
{
<one or more statements>
For example:
if( avg>70)
grade="distinction":
grade-"First Class";
else
grade=-"Second Class":
If you want to test whether a variable takes one ofa series of values, it's easier to usea
3. Switch Statement:
switch(<variable>)
The switch
statement
is found evaluates the value
among the constants
expression and then looks for its vaue among the case constants. If the
default listed. then the
(which is statements in that statement list are executed. Otherwise ifthere is a
optional),
an integer
then thee program breaks to that statement Note that expression must evaluate to
type and that the list.
Example:
constants must be integer
constaits.
switch(monthno)
case 1 :System.Console.WrtiteLine(n
break:
Jamuary ):
case 2: System.Console.
WtüeLine("nFebruary );
break:
;
break;
4. 4alltthrough in switch statement :In the absence of break statement in a case block, if the control moves
to the next case block without any problem, is known as "falthrough". C# does not permit automatic
it
Fallthrough, if the case block contains executable code. It is allowed if the case block is empty. In such cases goto
statement is used. The goto mechanism enables to jump backward and forward between cases and therefore
arrange labels arbitrarily. For example:
Switch(m)
defaut:xy-m;
break;
case 2:x=ytm;
goto default:
case 1:x=Y;
goto case 2:
5,
ternary
The 2: Onerator
operator. It
: C#inchudes
is the short form
a decision-making operator
of the if else conditions.
?: which is called the conditional operatoror
the first statement after ?. otherwise the second statement after :will be executed.
Page 17