0% found this document useful (0 votes)
756 views

C# Notes in Nepal

This document introduces C# programming language. It discusses that C# was developed by Microsoft as an object-oriented language that is part of the .NET framework. Some key features of C# discussed are that it is derived from C and C++ but is simpler and object-oriented, it supports inheritance, encapsulation and polymorphism, and has features like automatic garbage collection. The document also outlines the basic structure of a C# program, which includes documentation, using directives, classes, and a required Main method.

Uploaded by

Hello World
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
756 views

C# Notes in Nepal

This document introduces C# programming language. It discusses that C# was developed by Microsoft as an object-oriented language that is part of the .NET framework. Some key features of C# discussed are that it is derived from C and C++ but is simpler and object-oriented, it supports inheritance, encapsulation and polymorphism, and has features like automatic garbage collection. The document also outlines the basic structure of a C# program, which includes documentation, using directives, classes, and a required Main method.

Uploaded by

Hello World
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

1

Chapter: 1
Introduction to C#.NET

1.1 Introduce C# its Features and Applications


Introduce C#
C#' (pronounced as 'C sharp') is a new computer-programming
language developed by Microsoft Corporation, USA. C# is a fully
object-oriented language like Java and is the first Component-
oriented language. It has been designed to support the key
features of .NET Framework, the new development platform of
Microsoft for building component-based software solutions. It is a
simple, efficient, productive and type-safe language derived from
the popular C and C++ languages. Although it belongs to the family
of C/C++, it is a purely objected-oriented, modern language
suitable for developing Web based applications.

'C#' seems a strange name for a modern programming language. Perhaps Microsoft named
their new language 'C sharp' because they wanted it to be better, smarter and 'sharper' than
its ancestors C and C++, C# is designed to bring rapid development to C++ programmers
without sacrificing the power and control that have been the hallmarks of C and C++, C# is the
only language designed especially for the .NET platform which provides tools and services that
fully exploit both computing and communications.

Since one of the designers of C# (Anders Hejsberg) was a Java expert, it is natural that many
Java features have been incorporated into the design of C#. In fact, in many cases, the C# code
may bear a striking resemblance to the functionally equivalent Java code. Unlike C++, both
Java and C# promote a one-stop coding approach to code maintenance. They group classes,
interfaces and implementations together in one file so that programmers can edit the code
more easily.

C# is designed for building robust, reliable and durable components to handle real-world
applications. Major highlights of C# are:

• It is a brand-new language derived from the C/C++ family


• It simplifies and modernizes C++
• It is the only component-oriented language available today
• It is the only language designed for the .NET Framework
• It is a concise, lean and modern language
• It has a lean and consistent syntax

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
2

C# Features
The language that is designed for both computing and communication is characterised by
several key features. They are:

• Simple
• Object Oriented
• Compatible
• Consistent
• Modern
• Versionable

Simple:
C# simplifies C++ by eliminating irksome operators such as ->,:: and pointers. C# treats
integer and Boolean data types as two entirely different types. This means that the use of
in place of--in if statements will be caught by the compiler.

Object-Oriented
C# is truly object-oriented. It supports all the three tenets of object-oriented systems,
namely,

o Encapsulation
o Inheritance
o Polymorphism

Compatible
C# enforces the .NET common language specifications and therefore allows inter-
operation with other .NET languages. C# provides support for transparent access to
standard COM and OLE Automation. C# also permits interoperation with C-style APIs.

Consistent
C# supports a unified type system which eliminates the problem of varying ranges of
integer types. All types are treated as objects and developers can extend the type system
simply and easily.

Modern
C# is called a modern language due to a number of features it supports. It supports

o Automatic garbage collection


o Modern approach to debugging and
o Rich intrinsic model for error handling
o Robust security model
o Decimal data type for financial applications

Vesionable
Making new versions of software modules work with the existing applications is known
as versioning. C# provides support for versioning with the help of new and override

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
3

keywords. With this support, a programmer can guarantee that his new class library will
maintain binary compatibility with the existing client applications.

C# Applications
C# is a new language developed exclusively to suit the features of .NET platform. It can be
used for a variety of applications that are supported by the .NET platform:

• Console applications
• Windows applications
• Developing Windows controls
• Developing ASP.NET projects
• Creating Web controls
• Providing Web services

Development of C# .NET
Microsoft Chairman Bill Gates, the architect of many innovative and path-breaking software
products during the past two decades, wanted to develop a software platform which will
overcome these limitations and enable users to get information anytime and anywhere, using
a natural interface. The platform should be a collection of readily available Web services that
can be distributed and accessed via standard Internet protocols. He wanted to make the Web
both programmable and intelligent. The outcome is a new generation platform called .NET.
NET is simply the Microsoft's vision of 'software as a service.

Although the research and development work of .NET


platform began in the mid-90s, only during the
Microsoft Professional Developers Conference in
September 2000, was NET officially announced to the
developer community. At the same conference,
Microsoft introduced C# as a de facto language of the
.NET platform. In fact, they had already used C# to
code key modules of the .NET platform. C# has been
particularly designed to build software components
for .NET and supports key features of .NET natively. They are fairly tightly tied together. In
fact, C# compiler is embedded into .NET as shown in Fig.

1.2 Introduce the structure of C#


An executable C# program may contain a
number coding blocks as shown in Fig. The
documentation section consists of a set of
comments giving the name of the program,
the author, date and other details, which the
programmer (or other users) may like to use
at a later stage. Comments must explain,

o Why and what of classes, and the

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
4

o How of algorithms
This would greatly help maintaining the program.

The using directive section will include all those namespaces that contain classes required by
the application. using directives tell the compiler to look in the namespace specified for these
unresolved classes.

An interface 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.

A C# program may contain multiple class definitions. Classes are the primary and essential
elements of a C# program. These classes are used to map the objects of real-world problems.
The number of classes depends on the complexity of the problem.

Since every C# application program requires a Main method as its starting point, the class
containing the Main is the essential part of the program. A simple C# program may contain
only this part. The Main method creates objects of various classes and establishes
communications between them. On reaching the end of Main, the program terminates and
the control passes back to the operating system.

The code below is the basic structure of a C# program.

class SampleOne{
public static void Main(){
Console.WriteLine("C# is Sharper than C++.");
}
}

Class Declaration
The first line,

class SampleOne

declares a class, which is an object-oriented construct. As stated earlier, C# is a true object-


oriented language and therefore, 'everything' must be placed inside a class. class is a keyword
and declares that a new class definition follows. SampleOne is a C# identifier that specifies the
name of the class to be defined.

The Braces
C# is a block-structured language, meaning code blocks are always enclosed by braces { and }.
Therefore, every class definition in C# begins with an opening brace ‘{’ and ends with a
corresponding closing brace ‘}’ that appears in the last line of the program.

The Main Method


Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
5

The third line,

public static void Main()

defines a method named Main. Every C# executable program must include the Main() method
in one of the classes. This is the 'starting point for executing the program. A C# application can
have any number of classes but 'only one' class can have the Main method to initiate the
execution.

a. public
The keyword public is an access modifier that tells the C# compiler that the Main
method is accessible by anyone

b. static
The keyword static declares that the Main method is a global one and can be
called without creating an instance of the class. The compiler stores the address
of the method as the entry point and uses this information to begin execution
before any objects are created.

c. void
The keyword void is a type modifier that states that the Main method does not
return any value (but simply prints some text to the screen).

The Output Line


The only executable statement in the program is ,

System.Console.WriteLine("C# is sharper than C++.")

This has a striking resemblance to the output statement of Java and similar to the printf() of C
or cout<< of C++. Since C# is a pure object-oriented language, every method should be part of
an object. The WriteLine method is a static method of the Console class, which is located in
the namespace System. This line prints the string C# is sharper than C++ to the screen. The
method WriteLine always appends a new-line character to the end of the string. This means,
any subsequent output will start on a new line.

Note the semicolon at the end of the statement. Every C# statement must end with a
semicolon. And also note that there is no semicolon at the end of the class.

1.3 Analyze the variables of C#


A variable is an identifier that denotes a storage location used to store a data value. Unlike
constants that remain unchanged during the execution of a program, a variable may take
different values at different times during the execution of the program. Every variable has a
type that determines what values can be stored in the variable.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
6

A variable name can be chosen by the programmer in a meaningful way so as to reflect what
it represents in the program. Some examples of variable names are:

o Average
o total_height
o height
o classStrength

As mentioned earlier, variable names may consist of alphabets, digits and the underscore (__),
subject to the following conditions:

1. They must not begin with a digit.


2. Uppercase and lowercase are distinct. This means that the variable Total is not the
same as total or TOTAL.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.

Variables are the names of storage locations. After designing suitable variable names, we must
declare them to the compiler. Declaration does three things:

1. It tells the compiler what the variable name is.


2. It specifies what type of data the variable will hold.
3. The place of declaration (in the program) decides the scope of the variable. A variable
must be declared before it is used in the program.

A variable can be used to store a value of any data type. The general form of declaration
of a variable is:

type variable1, variable2, ........., variableN;

Example: int count;

float p1, p2

char character1;

A variable must be given a value after it has been declared but before it is used in an
expression. A simple method of giving value to a variable is through the assignment
statement as follows:

variableName = value;

or,

type variableName = value;

Example:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
7

value2 = 26;

float roll_no = 19;

1.4 Describe the Identifiers of C#


Identifiers are programmer-designed tokens. They are used for naming classes, methods,
variables, labels, namespaces, interfaces, etc. C# identifiers enforce the following rules:

o They can have alphabets, digits and underscore characters


o They must not begin with a digit
o Upper case and lower-case letters are distinct
o Keywords in stand-alone mode cannot be used as identifiers

C# permits the use of keywords as identifiers when they are prefixed with the '@' character

1.5 Introduce the keywords of C#


Keywords are an essential part of a language definition. They implement specific features of
the language. They are reserved, and cannot be used as identifiers except when they are
prefaced by the @ character. Below are the lists all the C# keywords:

abstract as base bool


break byte case catch
char checked class const
continue decimal default delegate
do double else enum
event explicit extern false
finally fixed float for
foreach goto if implicit
in in (generic modifier) int interface
internal is lock long
namespace new null object
operator out out (generic modifier) override
params private protected public
readonly ref return sbyte
sealed short sizeof stackalloc
static string struct switch
this throw true try
typeof uint ulong unchecked
unsafe ushort using using static
void volatile while

1.6 Explain data types in C#

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
8

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 a language rich in its data types.
The variety available allows the programmer to
select the type appropriate to the needs of the
application.
The types in C# are primarily divided into three
categories:

1. Value Type
2. Reference Type
3. Pointer

1. Value types
Value 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.

Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general,
and in our tutorial, the int data type is the preferred data type when we create variables
with a numeric value.
Example
int myNum = 100000;
Console.WriteLine(myNum);

Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note
that you should end the value with an "L":
Example
long myNum = 15000000000L;
Console.WriteLine(myNum);

Float
The float and double data types can store fractional numbers. Note that you should end
the value with an "F" for floats and "D" for doubles:
Example
float myNum = 5.75F;
Console.WriteLine(myNum);

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
9

Double
It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a
double variable, use the suffix d or D.
Example:

double d1 = 324.2D;

Console.WriteLine(d1);

Booleans
A boolean data type is declared with the bool keyword and can only take the values true
or false:
Example
bool isCSharpFun = true;
Console.WriteLine(isCSharpFun); // Outputs True

Characters
The char data type is used to store a single character. The character must be surrounded
by single quotes, like 'A' or 'c':
Example

char myGrade = 'B';

Console.WriteLine(myGrade);

Strings
The string data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
Example

string greeting = "Hello World";

Console.WriteLine(greeting);

Decimal Types
The decimal type is a 128-bit data type suitable for financial and monetary calculations. It
has 28–29-digit Precision.
Example

decimal sa = 72847;

Console.WriteLine(sa);

2. Reference types

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
10

Reference types (which are of variable length) are stored on the heap, and when an
assignment between two reference variables occurs, only the reference is copied; the
actual value remains in the same memory location. This means that there are two
references to a single value.

User-defined reference types refer to those types which we define using predefined types.
They include:

a. Classes
b. Delegates
c. Interfaces
d. Arrays

3. Pointer
A third category of types called pointers is available for use only in unsafe code. Value
types and reference types are further classified as predefined and user defined types
- & (ampersand) is the address operator used to determine the address of a
variable.
- * (asterisk) is indirection operator used to access the value of an address.

1.7 State the C# type conversion


Type conversion is converting one type of data to another type. It is also known as Type
Casting. Type casting is when you assign a value of one data type to another type.
The process of converting the value of one type (int, float, double, etc.) to another type is
known as type conversion.

The process of assigning a smaller type to a larger one is known as widening or promotion and
that of assigning a larger type to a smaller one is known as narrowing. Note that narrowing
may result in loss of information.

In C#, there are two basic types of type conversion:

1. Implicit Type Conversions


2. Explicit Type Conversions

1. Implicit Type Conversion


In implicit type conversion, the C# compiler automatically converts one type to another.
Generally, smaller types like int (having less memory size) are automatically converted to
larger types like double (having larger memory size).

char -> int -> long -> float -> double

An implicit conversion is also known as automatic type conversion.

Example:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
11

short sa = 26;

int ah = sa; // implicit conversion

float sk = 45232.23;

double as = sk; // implicit conversion

Code:

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int numInt = 500;

// get type of numInt


Type n = numInt.GetType();

// Implicit Conversion
double numDouble = numInt;

// get type of numDouble


Type n1 = numDouble.GetType();

// Value before conversion


Console.WriteLine("numInt value: " + numInt);
Console.WriteLine("numInt Type: " + n);

// Value after conversion


Console.WriteLine("numDouble value: " + numDouble);
Console.WriteLine("numDouble Type: " + n1);
Console.ReadLine();
}
}
}

Output:

numInt value: 500

numInt Type: System.Int32

numDouble value: 500

numDouble Type: System.Double

2. Explicit Type Conversion

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
12

In explicit type conversion, we explicitly convert one type to another.


Generally, larger types like double (having large memory size) are converted to smaller
types like int (having small memory size).

double -> float -> long -> int -> char

Explicit casting must be done manually by placing the type in parentheses in front of the
value. We can explicitly carry out such conversions using the 'cast' operator. The process
is known as casting and is done as follows:

type variable1 = (type) variable2;

Example:

int m = 50;
byte n = (byte) m;
long x = 1234L;
int y = (int) x;
float f = 50.OF;
long y = (long) f;

Code:

using System;
namespace MyApplication {
class Program {
static void Main(string[] args) {

double numDouble = 1.23;

// Explicit casting
int numInt = (int) numDouble;

// Value before conversion


Console.WriteLine("Original double Value: "+numDouble);

// Value before conversion


Console.WriteLine("Converted int Value: "+numInt);
Console.ReadLine();
}
}
}
Output:
Original double value: 1.23
Converted int value: 1

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
13

1.8 Introduce to C# operators


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. They usually
form a part of mathematical or logical expressions.

C# supports a rich set of operators. C# operators can be classified into a number of related
categories as below:

A. Arithmetic operators
B. Relational operators
C. Logical operators
D. Assignment operators
E. Conditional operators
F. Bitwise operators
G. Miscellaneous operators

A. Arithmetic Operator
Arithmetic operators are used to perform arithmetic operations such as addition,
subtraction, multiplication, division, etc. C# provides all the basic arithmetic operators.
The operators +, -, and / all work the same way as they do in other languages.

Operator Description Example


+ Adds two operands A + B = 30
- Subtracts second operand from the first A – B = -10
* Multiplies both operands A * B = 200
/ Divides numerator by de-numerator B/A=2
% Modulus Operator and remainder of after an integer division B%A=0
++ Increment operator increases integer value by one A++ = 11
-- Decrement operator decreases integer value by one A-- = 9

Code:

using System;
namespace Operators
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;
int c;
c = a + b;
Console.WriteLine("Line 1 - Value of c is {0}", c);
c = a - b;
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a * b;
Console.WriteLine("Line 3 - Value of c is {0}", c);
c = a / b;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
14

Console.WriteLine("Line 4 - Value of c is {0}", c);


c = a % b;
Console.WriteLine("Line 5 - Value of c is {0}", c);
c = a++;
Console.WriteLine("Line 6 - Value of c is {0}", c);
c = a--;
Console.WriteLine("Line 7 - Value of c is {0}", c);
Console.ReadLine();
}
}
}

Output:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

B. Relation Operator
Relational operators are used to check the relationship between two operands. If the
relationship is true the result will be true, otherwise it will result in false.
Relational operators are used in decision making and loops.

Operator Description Example


== Two operands are equal or not, if yes then condition (A == B) is not true.
becomes true.
!= Two operands are equal or not, if values are not equal (A != B) is true.
then condition becomes true.
> Left operand is greater than the value of right operand, (A > B) is not true.
if yes then condition becomes true.
< Left operand is less than the value of right operand, if (A < B) is true.
yes then condition becomes true.
>= Left operand is greater than or equal to the value of right (A >= B) is not true.
operand, if yes then condition becomes true.
<= Left operand is less than or equal to the value of right (A <= B) is true.
operand, if yes then condition becomes true.

Code:

using System;

class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
15

if (a == b)
{
Console.WriteLine("Line 1 - a is equal to b");
}
else
{
Console.WriteLine("Line 1 - a is not equal to b");
}

if (a < b)
{
Console.WriteLine("Line 2 - a is less than b");
}
else
{
Console.WriteLine("Line 2 - a is not less than b");
}

if (a > b)
{
Console.WriteLine("Line 3 - a is greater than b");
}
else
{
Console.WriteLine("Line 3 - a is not greater than b");
}

/* Lets change value of a and b */


a = 5;
b = 20;

if (a <= b)
{
Console.WriteLine("Line 4 - a is either less than or equal to b");
}

if (b >= a)
{
Console.WriteLine("Line 5-b is either greater than or equal to b");
}
}
}

Output:

Line 1 - a is not equal to b


Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
16

C. Logical Operator
Logical operators are used to perform logical operation such as and, or. Logical operators
operates on boolean expressions (true and false) and returns boolean values. Logical
operators are used in decision making and loops.

Operator Description Example


&& If both the operands are non-zero then condition (A && B) is false.
becomes true.
|| If any of the two operands is non zero then condition (A || B) is true.
becomes true.
! Use to reverses the logical state of its operand. If a !(A && B) is true.
condition is true then Logical NOT operator will make
false.

Code:

using System;

namespace OperatorsAppl {
class Program {
static void Main(string[] args) {
bool a = true;
bool b = true;

if (a && b) {
Console.WriteLine("Line 1 - Condition is true");
}

if (a || b) {
Console.WriteLine("Line 2 - Condition is true");
}

/* lets change the value of a and b */


a = false;
b = true;

if (a && b) {
Console.WriteLine("Line 3 - Condition is true");
} else {
Console.WriteLine("Line 3 - Condition is not true");
}

if (!(a && b)) {


Console.WriteLine("Line 4 - Condition is true");
}
Console.ReadLine();
}
}
}

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
17

Output:

Line 1 - Condition is true


Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

D. Assignment Operator
Assignment operators are used to assign the value of an expression to a variable. We have
seen the usual assignment operator, '='.

Operator Description Example


= Assigns values from right side operands to C = A + B assigns value of A + B into C
left side operand
+= It adds right operand to the left operand and C += A is equivalent to C = C + A
assign the result to left operand
-= It subtracts right operand from the left C -= A is equivalent to C = C - A
operand and assign the result to left
operand
*= It multiplies right operand with the left C *= A is equivalent to C = C * A
operand and assign the result to left
operand
/= It divides left operand with the right C /= A is equivalent to C = C / A
operand and assign the result to left
operand
%= It takes modulus using two operands and C %= A is equivalent to C = C % A
assign the result to left operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2
operator
|= bitwise inclusive OR and assignment C |= 2 is same as C = C | 2
operator

Code:

using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int c;
c = a;
Console.WriteLine("Line 1 - = Value of c = {0}", c);

c += a;
Console.WriteLine("Line 2 - += Value of c = {0}", c);

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
18

c -= a;
Console.WriteLine("Line 3 - -= Value of c = {0}", c);

c *= a;
Console.WriteLine("Line 4 - *= Value of c = {0}", c);

c /= a;
Console.WriteLine("Line 5 - /= Value of c = {0}", c);

c = 200;
c %= a;
Console.WriteLine("Line 6 - %= Value of c = {0}", c);

c <<= 2;
Console.WriteLine("Line 7 - <<= Value of c = {0}", c);

c >>= 2;
Console.WriteLine("Line 8 - >>= Value of c = {0}", c);

c &= 2;
Console.WriteLine("Line 9 - &= Value of c = {0}", c);

c ^= 2;
Console.WriteLine("Line 10 - ^= Value of c = {0}", c);

c |= 2;
Console.WriteLine("Line 11 - |= Value of c = {0}", c);
Console.ReadLine();
}
}
}

Output:

Line 1 - = Value of c = 21
Line 2 - += Value of c = 42
Line 3 - -= Value of c = 21
Line 4 - *= Value of c = 441
Line 5 - /= Value of c = 21
Line 6 - %= Value of c = 11
Line 7 - <<= Value of c = 44
Line 8 - >>= Value of c = 11
Line 9 - &= Value of c = 2
Line 10 - ^= Value of c = 0
Line 11 - |= Value of c = 2

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
19

E. Conditional Operator
Ternary operator is a Conditional operator in C#. It takes three arguments and evaluates
a Boolean expression.

b = (a == 1) ? 20 : 30;

Above, if the first operand evaluates to true (1), the second operand is evaluated. If the
first operand evaluates to false (0), the third operand is evaluated.

Code:
using System;
namespace DEMO {
class Program {
static void Main(string[] args) {
int a, b;
a = 10;
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);

b = (a == 10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
Console.ReadLine();
}
}
}

Output:
Value of b is 30
Value of b is 20

F. Bitwise Operator
Bitwise and bit shift operators are used to perform bit manipulation operations.

Operator Description Example


& Binary AND Operator copies a bit to the (A & B) = 12, which is 0000 1100
result if it exists in both operands.
| Binary OR Operator copies a bit if it exists (A | B) = 61, which is 0011 1101
in either operand.
^ Binary XOR Operator copies the bit if it is (A ^ B) = 49, which is 0011 0001
set in one operand but not both.
~ Binary Ones Complement Operator is (~A ) = -61, which is 1100 0011 in 2's
unary and has the effect of 'flipping' bits.
complement due to a signed binary
number.
<< Binary Left Shift Operator. The left A << 2 = 240, which is 1111 0000
operands value is moved left by the
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left A >> 2 = 15, which is 0000 1111
operands value is moved right by the

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
20

number of bits specified by the right


operand.

Code:
using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


Console.WriteLine("Line 1 - Value of c is {0}", c);

c = a | b; /* 61 = 0011 1101 */
Console.WriteLine("Line 2 - Value of c is {0}", c);

c = a ^ b; /* 49 = 0011 0001 */
Console.WriteLine("Line 3 - Value of c is {0}", c);

c = ~a; /*-61 = 1100 0011 */


Console.WriteLine("Line 4 - Value of c is {0}", c);

c = a << 2; /* 240 = 1111 0000 */


Console.WriteLine("Line 5 - Value of c is {0}", c);

c = a >> 2; /* 15 = 0000 1111 */


Console.WriteLine("Line 6 - Value of c is {0}", c);
Console.ReadLine();
}
}
}

Output:

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
21

G. Miscellaneous Operator
Operator Description Example
sizeof() Returns the size of a data type. sizeof(int), returns 4.
typeof() Returns the type of a class. typeof(StreamReader);
& Returns the address of an variable. &a; returns actual address of the
variable.
* Pointer to a variable. *a; creates pointer named 'a' to a
variable.
?: Conditional Expression If Condition is true ? Then value X :
Otherwise value Y
is Determines whether an object is of a If( Ford is Car) // checks if Ford is an
certain type. object of the Car class.
as Cast without raising an exception if the Object obj = new
cast fails. StringReader("Hello");
StringReader r = obj as StringReader;

Example:
using System;
namespace OperatorsAppl {
class Program {

static void Main(string[] args) {


/* example of sizeof operator */
Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of short is {0}", sizeof(short));
Console.WriteLine("The size of double is {0}", sizeof(double));

/* example of ternary operator */


int a, b;
a = 10;
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);

b = (a == 10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
Console.ReadLine();
}
}
}

Output:

The size of int is 4


The size of short is 2
The size of double is 8
Value of b is 30
Value of b is 20

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
22

Chapter: 2
Control Statements

2.1 Introduce the control statements


When a program breaks the sequential flow and jumps to another part of the code, it is called
branching. When the branching is based on a particular condition, it is known as conditional
branching. If branching takes place without any decision, it is known as unconditional
branching.

C# language possesses such decision-making capabilities and supports the following


statements known as control or decision-making statements.

1. if statement
2. if else statement
3. if else if else statement
4. switch statement

2.2 Demonstrate if, if else and if else ladder and compute it


1. if statement
The if statement checks the given condition. If the condition evaluates to be true then the
block of code/statements will execute otherwise not.

Syntax:
if(condition)
{
//statements
}

Code:
using System;

public class GFG {

public static void Main(string[] args)


{
string name = "Sam";
if (name == "Sam") {
Console.WriteLine("If statement executed.");
}
}
}

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
23

Output:
If statement executed.

2. if else statement
The if statement evaluates the code if the condition is true but what if the condition is not
true, here comes the else statement. It tells the code what to do when the if condition is
false.

Syntax:
if(condition)
{
// code if condition is true
}
else
{
// code if condition is false
}

Code:
using System;
public class GFG {

public static void Main(string[] args)


{
string name = "Sam";
if (name == "Sam") {
Console.WriteLine("If statement executed.");
}
else {
Console.WriteLine("Else statement executed.");
}
}
}

Output:
Else statement executed.

3. if else if else 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)

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
24

{
// 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
}
...
else
{
// code to be executed if all the conditions are false
}

Code:

using System;

class GFG {

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");
}
}

Output:
i is 20

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
25

2.3 Demonstrate the switch statement and its functions


4. Switch Statement
A switch statement allows a variable to be tested for equality against a list of values. There
is default case (optional) at the end of switch, if none of the case matches then default
case is executed.

It provides an efficient way to transfer the execution to different parts of a code based on
the value of the expression.

Syntax:

switch (expression)
{
case value1: // statement sequence
break;
case value2: // statement sequence
break;
.
.
.
case valueN: // statement sequence
break;
default: // default statement sequence
}

Code:
using System;

public class GFG


{
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 matches");
break;
}
}
}

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
26

Output:
case 30

2.4 Illustrate the for loop and deduce its usage


The process of repeatedly executing a block of statements is known as looping. The
statements in the block may be executed any number of times, from zero to an infinite
number. Loops are of two types:

A. Entry Control Loop:


The loops in which condition to be tested is present in beginning of loop body are known
as Entry Controlled Loops.
1. For Loop
2. While Loop
3. For Each Loop

B. Exit Control Loop


The loops in which the testing condition is present at the end of loop body are termed as
Exit Controlled Loops.
4. Do while Loop

1. For Loop
for loop has similar functionality as while loop but with different syntax. The loop variable
initialization, condition to be tested, and increment/decrement of the loop variable is
done in one line in for loop thereby providing a shorter, easy to debug structure of looping.

- Initialization of loop variable: The expression / variable controlling the loop is


initialized here. It is the starting point of for loop.

- Testing Condition: It is used for testing the exit condition for a loop. It must return
a boolean value true or false.

- Increment / Decrement: The loop variable is incremented/decremented


according to the requirement and the control then shifts to the testing condition
again.

Syntax:
for (loop variable initialization ; testing condition; increment / decrement)
{
// statements to be executed
}

Code:
using System;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
27

class forLoopDemo
{
public static void Main()
{
// for loop begins when x=1
// and runs till x <=4
for (int x = 1; x <= 4; x++)
Console.WriteLine("Sam {0}", x);
}
}

Output:
Sam 1
Sam 2
Sam 3
Sam 4

2.5 Illustrate the do while loop and deduce its usage.


2. While Loop:
The test condition is given in the beginning of the loop and all statements are executed
till the given boolean condition satisfies when the condition becomes false, the control
will be out from the while loop.

Syntax:
while (boolean condition)
{
loop statements...
}

Code:
using System;

class whileLoopDemo
{
public static void Main()
{
int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
Console.WriteLine("Sam {0}", x);
x++;
}
}
}

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
28

Output:
Sam 1
Sam 2
Sam 3
Sam 4

3. For each
C# provides an easy to use and more readable alternative to for loop, the foreach loop
when working with arrays and collections to iterate through the items of
arrays/collections. The foreach loop iterates through each item, hence called foreach
loop.

Syntax:
foreach(data_type var_name in collection_variable)
{
// statements to be executed
}

Code:

using System;

class GFG {

// Main Method

static public void Main()

Console.WriteLine("Print array:");

int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 };

foreach(int items in a_array)

Console.WriteLine(items);

Output:

Print array:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
29

2.6 Illustrate the while loop and deduce its usage


1. Do while Loop
do while loop is similar to while loop with the only difference that it checks the condition
after executing the statements, i.e. it will execute the loop body one time for sure because
it checks the condition after executing the statements.

Syntax:
do
{
statements..
} while (condition);

Code:
using System;

class dowhileloopDemo
{
public static void Main()
{
int x = 21;
do
{
// The line will be printed even
// if the condition is false
Console.WriteLine("Sam");
x++;
}
while (x < 20);
}
}

Output:
Sam

2.7 Classify loop control statements and compare its feature

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
30

Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed.

C# provides the following control statements.

2. break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.

Syntax:
break;
Code:
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;

/* while loop execution */


while (a < 20) {
Console.WriteLine("value of a: {0}", a);
a++;

if (a > 15) {
/* terminate the loop using break statement */
break;
}
}
Console.ReadLine();
}
}
}

Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

3. continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.

Syntax:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
31

continue;

Code:
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;

/* do loop execution */
do {
if (a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;
}
while (a < 20);
Console.ReadLine();
}
}
}

Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

4. goto statement
The C# goto statement is also known jump statement. It is used to transfer control to the
other part of the program. It unconditionally jumps to the specified label.
It can be used to transfer control from deeply nested loop or switch case label.

Currently, it is avoided to use goto statement in C# because it makes the program


complex.

Code:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
32

using System;
public class GotoExample
{
public static void Main(string[] args)
{
ineligible:
Console.WriteLine("You are not eligible to vote!");

Console.WriteLine("Enter your age:\n");


int age = Convert.ToInt32(Console.ReadLine());
if (age < 18){
goto ineligible;
}
else
{
Console.WriteLine("You are eligible to vote!");
}
}
}
Output:
You are not eligible to vote!
Enter your age:
11
You are not eligible to vote!
Enter your age:
5
You are not eligible to vote!
Enter your age:
26
You are eligible to vote!

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
33

Chapter: 3
Array

3.1 Introduce the arrays and its usage


An array is a group of contiguous or related data items that share a common name. For
instance, we can define an array name marks to represent a set of marks of a class of students.
A particular value is indicated by writing a number called index number or subscript in brackets
after the array name.

Usage:

You can store multiple values in a single variable by using array in C#.

3.2 Demonstrate the declaration and initialization of array


Declaration:
Syntax:

type[] arrayname;

Examples:

int[] counter; //declare int array reference

float[] x,y;

Creation:
After declaring an array, we need to create it in the memory. C# allows us to create arrays
using new operator only.

Syntax:

arrayname new type[size];

Examples:

number new int[5]; //create a 5 element int array

average new float[10]; // create a 10 element float array

Initialization:
Initialization of Arrays

This process is known as initialization.

Syntax:

arrayname[subscript] = value;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
34

Example:

number[0] = 26;

number[1] = 19;

number[2] = 0;

number[3] = 22;

number[4] = 18;

Note that C# creates arrays starting with a subscript of 0 and ends with a value one less than
the size specified.

We can also initialize arrays automatically in the same way as the ordinary variables when
they are declared, as shown below:

type [] arrayname = {list of values);

Example:

int[] number [35, 40, 20, 57, 19};

3.3 Illustrate the data access from an array


An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example,

double salary = balance[9];

Code:

using System;

namespace ArrayApplication {

class MyArray {

static void Main(string[] args) {

int [] n = new int[10]; /* n is an array of 10 integers */

int i,j;

/* initialize elements of array n */

for ( i = 0; i < 10; i++ ) {

n[ i ] = i + 100;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
35

/* output each array element's value */

for (j = 0; j < 10; j++ ) {

Console.WriteLine("Element[{0}] = {1}", j, n[j]);

Console.ReadKey();

Example:

Element[0] = 100

Element[1] = 101

Element[2] = 102

Element[3] = 103

Element[4] = 104

Element[5] = 105

Element[6] = 106

Element[7] = 107

Element[8] = 108

Element[9] = 109

3.4 Introduce to multidimensional arrays


C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array.
You can declare a 2-dimensional array of strings as −

string [,] names;

or, a 3-dimensional array of int variables as −

int [ , , ] m;

Two-Dimensional Arrays
The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional
array is a list of one-dimensional arrays.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
36

A 2-dimensional array can be thought of as a table, which has x number of rows and y number
of columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns:

Thus, every element in the array a is identified by an element name of the form a[ i , j ], where
a is the name of the array, and i and j are the subscripts that uniquely identify each element
in array a.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row. The
Following array is with 3 rows and each row has 4 columns.

int [,] a = new int [3,4] {

{0, 1, 2, 3} , /* initializers for row indexed by 0 */

{4, 5, 6, 7} , /* initializers for row indexed by 1 */

{8, 9, 10, 11} /* initializers for row indexed by 2 */

};

Accessing Two-Dimensional Array Elements


An element in 2-dimensional array is accessed by using the subscripts. That is, row index and
column index of the array.

Syntax:

int val = a[2,3];

Code:

using System;

namespace ArrayApplication {

class MyArray {

static void Main(string[] args) {

/* an array with 5 rows and 2 columns*/

int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
37

int i, j;

/* output each array element's value */

for (i = 0; i < 5; i++) {

for (j = 0; j < 2; j++) {

Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);

Console.ReadKey();

Output:

a[0,0]: 0

a[0,1]: 0

a[1,0]: 1

a[1,1]: 2

a[2,0]: 2

a[2,1]: 4

a[3,0]: 3

a[3,1]: 6

a[4,0]: 4

a[4,1]: 8

3.5 Compare and deduce the applications of jagged arrays,


param arrays, and array class
1. Jagged Arrays
A Jagged array is an array of arrays. You can declare a jagged array named scores of
type int as −

int [][] scores;

Declaring an array, does not create the array in memory. To create the above array −

int[][] scores = new int[5][];

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
38

for (int i = 0; i < scores.Length; i++) {

scores[i] = new int[4];

You can initialize a jagged array as −

int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};

Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers


and scores[1] is an array of 4 integers.

Example:

using System;

namespace ArrayApplication {

class MyArray {

static void Main(string[] args) {

/* a jagged array of 5 array of integers*/

int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},

new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };

int i, j;

/* output each array element's value */

for (i = 0; i < 5; i++) {

for (j = 0; j < 2; j++) {

Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);

Console.ReadKey();

Output:

a[0][0]: 0

a[0][1]: 0

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
39

a[1][0]: 1

a[1][1]: 2

a[2][0]: 2

a[2][1]: 4

a[3][0]: 3

a[3][1]: 6

a[4][0]: 4

a[4][1]: 8

2. Parma Array
At times, while declaring a method, you are not sure of the number of arguments
passed as a parameter. C# param arrays (or parameter arrays) come into help at such
times.

Code:
using System;
namespace ArrayApplication {
class ParamArray {
public int AddElements(params int[] arr) {
int sum = 0;

foreach (int i in arr) {


sum += i;
}
return sum;
}
}
class TestClass {
static void Main(string[] args) {
ParamArray app = new ParamArray();
int sum = app.AddElements(512, 720, 250, 567, 889);

Console.WriteLine("The sum is: {0}", sum);


Console.ReadKey();
}
}
}
Output:
The sum is: 2938

3. Array Class
The Array class is the base class for all the arrays in C#. It is defined in the System
namespace. The Array class provides various properties and methods to work with
arrays.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
40

Properties of the Array Class


The following table describes some of the most commonly used properties of the
Array class –

Sr.No. Property & description


1 IsFixedSize
Gets a value indicating whether the Array has a fixed size.
2 IsReadOnly
Gets a value indicating whether the Array is read-only.
3 Length
Gets a 32-bit integer that represents the total number of elements in all
the dimensions of the Array.
4 LongLength
Gets a 64-bit integer that represents the total number of elements in all
the dimensions of the Array.
5 Rank
Gets the rank (number of dimensions) of the Array.

Methods of the Array Class


The following table describes some of the most commonly used methods of the Array
class −

Sr.No. Methods & Description


1 Clear
Sets a range of elements in the Array to zero, to false, or to null,
depending on the element type.
2 Copy(Array, Array, Int32)
Copies a range of elements from an Array starting at the first element
and pastes them into another Array starting at the first element. The
length is specified as a 32-bit integer.
3 CopyTo(Array, Int32)
Copies all the elements of the current one-dimensional Array to the
specified one-dimensional Array starting at the specified destination
Array index. The index is specified as a 32-bit integer.
4 GetLength
Gets a 32-bit integer that represents the number of elements in the
specified dimension of the Array.
5 GetLongLength
Gets a 64-bit integer that represents the number of elements in the
specified dimension of the Array.
6 GetLowerBound
Gets the lower bound of the specified dimension in the Array.
7 GetType
Gets the Type of the current instance. (Inherited from Object.)
8 GetUpperBound
Gets the upper bound of the specified dimension in the Array.
9 GetValue(Int32)

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
41

Gets the value at the specified position in the one-dimensional Array.


The index is specified as a 32-bit integer.
10 IndexOf(Array, Object)
Searches for the specified object and returns the index of the first
occurrence within the entire one-dimensional Array.
11 Reverse(Array)
Reverses the sequence of the elements in the entire one-dimensional
Array.
12 SetValue(Object, Int32)
Sets a value to the element at the specified position in the one-
dimensional Array. The index is specified as a 32-bit integer.
13 Sort(Array)
Sorts the elements in an entire one-dimensional Array using the
IComparable implementation of each element of the Array.
14 ToString
Returns a string that represents the current object. (Inherited from
Object.)

Code:
using System;

namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
int[] temp = list;
Console.Write("Original Array: ");

foreach (int i in list) {


Console.Write(i + " ");
}
Console.WriteLine();

// reverse the array


Array.Reverse(temp);
Console.Write("Reversed Array: ");

foreach (int i in temp) {


Console.Write(i + " ");
}
Console.WriteLine();

//sort the array


Array.Sort(list);
Console.Write("Sorted Array: ");

foreach (int i in list) {


Console.Write(i + " ");
}

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
42

Console.WriteLine();
Console.ReadKey();
}
}
}

Output:
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
43

Chapter: 4
String

4.1 Introduce the strings, its usages and functions


C# supports a predefined reference type known as string. We can use string to declare string
type objects. Remember, when we declare a string using string type, we are in fact declaring
the object to be of type System.String, one of the built-in types provided by the .NET
Framework. A string type is therefore a System.String type as well.

Usage of string
Most programming languages have a data type called a string, which is used for data values
that are made up of ordered sequences of characters, such as "hello world". A string can
contain any sequence of characters, visible or invisible, and characters may be repeated. The
main usage of string is to store a sequence of characters together in a variable.

4.2 Demonstrate the creation of a string object


We can create immutable strings using string or String objects in a number of ways.

• Assigning string literals


• Copying from one object to another
• Concatenating two objects
• Reading from the keyboard
• Using ToString method.

Code:

using System;

namespace CsharpString {

class Test {

public static void Main(string [] args) {

// create string

string str1 = "C# Programming";

string str2 = "Microsoft";

// print string

Console.WriteLine(str1);

Console.WriteLine(str2);

Console.ReadLine();

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
44

Output:

C# Programming

Microsoft

4.3 Demonstrate the methods of string class and deduce its


usages
4.4 Introduce to string functions and examine the usage of
functions
String objects are immutable, meaning that we cannot modify the characters contained in
them. However, since the string is an alias for the predefined System.String class in the
Common Language Runtime (CLR), there are many built-in operations available that work with
strings. All operations produce a modified version of the string rather than modifying the
string on which the method is called.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
45

Code:

using System;

class HelloWorld

static void Main()

string str = "Hello World";

Console.WriteLine(str.Length);

Console.WriteLine(str.ToUpper());

Console.WriteLine(str.ToLower());

Console.WriteLine(str.Trim());

Console.WriteLine(str.Replace("World", "C#"));

Console.WriteLine(str.Substring(6, 5));

string[] words = str.Split(' ');

foreach (string word in words)

Console.WriteLine(word);

Console.WriteLine(str.IndexOf("World"));

Console.WriteLine(str.LastIndexOf("World"));

Console.WriteLine(str.Insert(6, "C#"));

Console.WriteLine(str.Remove(6, 3));

Console.WriteLine(str.PadLeft(20));

Console.WriteLine(str.PadRight(20));

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
46

char[] chars = str.ToCharArray();

foreach (char ch in chars)

Console.WriteLine(ch);

Output:

11HELLO WORLD

hello world

Hello World

Hello C#World

Hello

World

Hello C#World

Hello ld

Hello World

Hello World

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
47

Reading from the Keyboard


It is possible to read a string value interactively from the keyboard and assign it to a string
object.

string s = Console.ReadLine();

On reaching this statement, the computer will wait for a string of characters to be entered
from the keyboard. When the 'return key' is pressed, the string will be read and assigned to
the string object s.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
48

Chapter: 5
Structure

5.1 Introduction to structure, its features and its necessities


Structures (often referred to as structs) are similar to classes in C#. Although classes will be
used to implement most objects, it is desirable to use structs where simple composite data
types are required. Because they are value types stored on the stack, they have the following
advantages compared to class objects stored on the heap:

o They are created much more quickly than heap-allocated types.


o They are instantly and automatically deallocated once they go out of scope.
o It is easy to copy value type variables on the stack.

The performance of programs may be enhanced by judicious use of structs.

Features of Structure
• Structures can have methods, fields, indexers, properties, operator methods, and
events.
• Unlike classes, structures cannot inherit other structures or classes.
• Structures cannot be used as a base for other structures or classes.
• A structure can implement one or more interfaces.
• Structure members cannot be specified as abstract, virtual, or protected.

Necessities of Structure
Structure is necessary because it helps you to create class of different datatype and make as
much object of it as required in the program. Structure is a user-defined datatype in C
language which allows us to combine data of different types together. Structure helps to
construct a complex data type which is more meaningful. It is somewhat similar to an Array,
but an array holds data of similar type only, but structure can hold different datatypes.

5.2 Demonstration of Defining of structure and its usage


Structs are declared using the struct keyword. The simple form of a struct definition is as
follows:

struct struct-name
{
data member1;
data member2;
. . .
. . .
}

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
49

Example:

struct Student{

string name;

int class;

int roll;

To create and item or object of the structure we need to use the following syntax:

struct-name item-name;

Example:

Student s1;

Assigning Values to Members


Member variables can be accessed using the simple dot notation as follows:

item-name.variabl_name;

Example:

s1.name = “Sam”;

s1.class = 9;

s1.roll = 22;

Code:

using System;

struct Books {

public string title;

public string author;

public string subject;

public int book_id;

};

public class testStructure {

public static void Main(string[] args) {

Books Book1; /* Declare Book1 of type Book */

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
50

Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */

Book1.title = "C Programming";

Book1.author = "Nuha Ali";

Book1.subject = "C Programming Tutorial";

Book1.book_id = 6495407;

/* book 2 specification */

Book2.title = "Telecom Billing";

Book2.author = "Zara Ali";

Book2.subject = "Telecom Billing Tutorial";

Book2.book_id = 6495700;

/* print Book1 info */

Console.WriteLine( "Book 1 title : {0}", Book1.title);

Console.WriteLine("Book 1 author : {0}", Book1.author);

Console.WriteLine("Book 1 subject : {0}", Book1.subject);

Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);

/* print Book2 info */

Console.WriteLine("Book 2 title : {0}", Book2.title);

Console.WriteLine("Book 2 author : {0}", Book2.author);

Console.WriteLine("Book 2 subject : {0}", Book2.subject);

Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);

Console.ReadKey();

Output:

Book 1 title : C Programming

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
51

Book 1 author : Nuha Ali

Book 1 subject : C Programming Tutorial

Book 1 book_id : 6495407

Book 2 title : Telecom Billing

Book 2 author : Zara Ali

Book 2 subject : Telecom Billing Tutorial

Book 2 book_id : 6495700

5.3 Compare and evaluate class vs structure and


demonstrate it

Code:

using System;

public struct Rectangle

public int width, height;

public Rectangle(int w, int h)

width = w;

height = h;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
52

public void areaOfRectangle() {

Console.WriteLine("Area of Rectangle is: "+(width*height)); }

public class TestStructs

public static void Main()

Rectangle r = new Rectangle(5, 6);

r.areaOfRectangle();

Output:

Area of Rectangle is: 30

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
53

Chapter: 6
Pointer

6.1 Introduce the pointers, its features and its applications


A pointer is a variable whose value is the address of another variable i.e., the direct
address of the memory location. Similar to any variable or constant, you must declare
a pointer before you can use it to store any variable address.

The general form of a pointer declaration is:


type *var-name;

Example:
int *sa;
double *as;

Code:
using System;
namespace UnsafeCodeApplication
{
class Program
{
static unsafe void Main(string[] args)
{
int var = 20;
int* p = &var;
Console.WriteLine("Data is: {0} ", var);
Console.WriteLine("Address is: {0}", (int)p);
Console.ReadKey();
}
}
}

Output:

Data is: 20

Address is: 99215364

Features of Pointer
• Pointers save memory space.
• Execution time with pointers is faster because data are manipulated with the address,
that is, direct access to memory location.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
54

• Memory is accessed efficiently with the pointers. The pointer assigns and releases the
memory as well.
• Pointers are used with data structures. They are useful for representing two-
dimensional and multi-dimensional arrays.
• Pointers are used for file handling.
• Pointers are used to allocate memory dynamically.1

Application of Pointer
• To pass arguments by reference
• For accessing array elements
• To return multiple values
• Dynamic memory allocation
• To implement data structures

6.2 Differentiate between advantages and disadvantages of


pointers
Advantages:
• Pointers provide direct access to memory
• Pointers provide a way to return more than one value to the functions
• Reduces the storage space and complexity of the program
• Reduces the execution time of the program
• Provides an alternate way to access array elements
• Pointers allows us to perform dynamic memory allocation and deallocation.

Disadvantages:
• Uninitialized pointers might cause segmentation fault.
• Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
• Pointers are slower than normal variables.
• If pointers are updated with incorrect values, it might lead to memory corruption.

6.3 Demonstrate the access of data value using pointer


Code:

using System;

namespace UnsafeCodeApplication

class Program

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
55

public static void Main()

unsafe

// {

int var = 20;

int* p = &var;

Console.WriteLine("Data is: {0} ", var);

Console.WriteLine("Data is: {0} ", p->ToString());

Console.WriteLine("Address is: {0} ", (int)p);

Console.ReadKey();

Output:

Data is: 20

Data is: 20

Address is: 77128984

6.4 Illustrate the passing of pointers as parameters to


methods
Code:

using System;

namespace UnsafeCodeApplication

class TestPointer

public unsafe void swap(int* p, int* q)

int temp = *p;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
56

*p = *q;

*q = temp;

public unsafe static void Main()

TestPointer p = new TestPointer();

int var1 = 10;

int var2 = 20;

int* x = &var1;

int* y = &var2;

Console.WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2);

p.swap(x, y);

Console.WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2);

Console.ReadKey();

Output:

Before Swap: var1: 10, var2: 20

After Swap: var1: 20, var2: 10

6.5 Demonstrate the access of array elements using a pointer


Code:

using System;

namespace UnsafeCodeApplication

class TestPointer

public unsafe static void Main()

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
57

int[] list = { 10, 100, 200 };

fixed (int* ptr = list)

/* let us have array address in pointer */

for (int i = 0; i < 3; i++)

Console.WriteLine("Address of list[{0}]={1}", i, (int)(ptr + i));

Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i));

Console.ReadKey();

Output:

Address of list[0] = 31627168

Value of list[0] = 10

Address of list[1] = 31627172

Value of list[1] = 100

Address of list[2] = 31627176

Value of list[2] = 200

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
58

Chapter: 7
Working with database

7.1 Introduce the database, its features and necessity in


programming environment
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system. A database is usually controlled by a database
management system (DBMS). Together, the data and the DBMS, along with the applications
that are associated with them, are referred to as a database system, often shortened to just
database.

Features of Database
• Minimum Redundancy and Duplication
• Reduced amount of space and money spent on storage
• Data Organization
• Data Retrieval
• Usage Of Query Languages
• Multi User Access
• Data Integrity is Maintained
• Provides a High Level of Data Security

Necessity of Database in Programming Environment


• Data Integrity: This means that the structure of the database can change, but the
application that uses the data does not have to change.
• Data Consistency: The data is identical regardless of who is inspecting it.

• Data Backups: Backing up data from a single location is simple.
• Data Security: Data can only be accessed by the authorized users.
• Data Redundancy: Duplication of the data is minimized.
• Data Durability: Database will persist even after a power loss or a disaster.

7.2 Demonstrate the Database environment setup and


configure the requirements
To be written….

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
59

7.3 Illustrate the connection of C# program with database


C# and .Net can work with a majority of databases, the most common being Oracle and
Microsoft SQL Server. But with every database, the logic behind working with all of them is
mostly the same.

Connecting C# with Database: To work with a database, the first of all you required a
connection. The connection to a database normally consists of the below-mentioned
parameters.

• Database name or Data Source: The database name to which the connection needs
to be set up and connection can be made or you can say only work with one database
at a time.
• Credentials: The username and password which needs to be used to establish a
connection to the database.
• Optional Parameters: For each database type, you can specify optional parameters to
provide more information on how .NET should connect to the database to handle the
data.

Code:

// C# code to connect the database


using System;
using System.Data.SqlClient;
class DBConn
{

// Main Method
static void Main()
{
Connect();
Console.ReadKey();
}

static void Connect()


{
string constr;

// for the connection to sql server database


SqlConnection conn;

// Data Source is the name of the


// server on which the database is stored.
// The Initial Catalog is used to specify
// the name of the database
// The UserID and Password are the credentials
// required to connect to the database.
constr = @"Data Source=demo;Initial Catalog=demo;User ID=demo;Password=demo";
conn = new SqlConnection(constr);

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
60

// to open the connection


conn.Open();
Console.WriteLine("Connection Open!");

// to close the connection


conn.Close();
}
}

Output:

Connection Open !

7.4 Demonstrate the Read and write operations from the


database
Read form database:
Code:

// C# code to demonstrate how

// to use select statement

using System;
using System.Data.SqlClient;

namespace Database_Operation
{

class SelectStatement
{

// Main Method
static void Main()
{
Read();
Console.ReadKey();
}

static void Read()


{
string constr;

// for the connection to


// sql server database
SqlConnection conn;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
61

// Data Source is the name of the


// server on which the database is stored.
// The Initial Catalog is used to specify
// the name of the database
// The UserID and Password are the credentials
// required to connect to the database.
constr = @"Data Source=demo;Initial Catalog=demo;User
ID=demo;Password=demo";

conn = new SqlConnection(constr);

// to open the connection


conn.Open();

// use to perform read and write


// operations in the database
SqlCommand cmd;

// use to read a row in


// table one by one
SqlDataReader dreader;

// to sore SQL command and


// the output of SQL command
string sql, output = "";

// use to fetch rows from demo table


sql = "Select articleID, articleName from demoTable";

// to execute the sql statement


cmd = new SqlCommand(sql, conn);

// fetch all the rows


// from the demo table
dreader = cmd.ExecuteReader();

// for one by one reading row


while (dreader.Read())
{
output = output + dreader.GetValue(0) + " - " + dreader.GetValue(1) + "\n";
}

// to display the output


Console.Write(output);

// to close all the objects


dreader.Close();

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
62

cmd.Dispose();
conn.Close();
}
}
}

Output:

1 - C#

2 - C++

Write to database
Code:

// C# code for how to use Insert Statement

using System;
using System.Data.SqlClient;

namespace Database_Operation {

class InsertStatement {

// Main Method
static void Main()
{
Insert();
Console.ReadKey();
}

static void Insert()


{
string constr;

// for the connection to


// sql server database
SqlConnection conn;

// Data Source is the name of the


// server on which the database is stored.
// The Initial Catalog is used to specify
// the name of the database
// The UserID and Password are the credentials
// required to connect to the database.
constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User
ID=sa;Password=24518300";

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
63

conn = new SqlConnection(constr);

// to open the connection


conn.Open();

// use to perform read and write


// operations in the database
SqlCommand cmd;

// data adapter object is use to


// insert, update or delete commands
SqlDataAdapter adap = new SqlDataAdapter();

string sql = "";

// use the defined sql statement


// against our database
sql = "insert into demo values(3, 'Python')";

// use to execute the sql command so we


// are passing query and connection object
cmd = new SqlCommand(sql, conn);

// associate the insert SQL


// command to adapter object
adap.InsertCommand = new SqlCommand(sql, conn);

// use to execute the DML statement against


// our database
adap.InsertCommand.ExecuteNonQuery();

// closing all the objects


cmd.Dispose();
conn.Close();
}
}
}

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta

You might also like