C# Notes in Nepal
C# Notes in Nepal
Chapter: 1
Introduction to C#.NET
'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:
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
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.
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.
class SampleOne{
public static void Main(){
Console.WriteLine("C# is Sharper than C++.");
}
}
Class Declaration
The first line,
class SampleOne
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.
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).
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.
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:
Variables are the names of storage locations. After designing suitable variable names, we must
declare them to the compiler. Declaration does three things:
A variable can be used to store a value of any data type. The general form of declaration
of a variable is:
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,
Example:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
7
value2 = 26;
C# permits the use of keywords as identifiers when they are prefixed with the '@' character
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
8
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
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
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.
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.
Example:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
11
short sa = 26;
float sk = 45232.23;
Code:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int numInt = 500;
// Implicit Conversion
double numDouble = numInt;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
12
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:
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) {
// Explicit casting
int numInt = (int) numDouble;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
13
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.
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
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.
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");
}
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:
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.
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");
}
if (a && b) {
Console.WriteLine("Line 3 - Condition is true");
} else {
Console.WriteLine("Line 3 - Condition is not true");
}
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
17
Output:
D. Assignment Operator
Assignment operators are used to assign the value of an expression to a variable. We have
seen the usual assignment 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.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
20
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; /* 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);
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 {
b = (a == 10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
Console.ReadLine();
}
}
}
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
22
Chapter: 2
Control Statements
1. if statement
2. if else statement
3. if else if else statement
4. switch statement
Syntax:
if(condition)
{
//statements
}
Code:
using System;
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 {
Output:
Else statement executed.
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 {
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
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;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
26
Output:
case 30
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.
- Testing Condition: It is used for testing the exit condition for a loop. It must return
a boolean value true or false.
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
Syntax:
while (boolean condition)
{
loop statements...
}
Code:
using System;
class whileLoopDemo
{
public static void Main()
{
int x = 1;
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
Console.WriteLine("Print array:");
Console.WriteLine(items);
Output:
Print array:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
29
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
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.
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;
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.
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!");
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
33
Chapter: 3
Array
Usage:
You can store multiple values in a single variable by using array in C#.
type[] arrayname;
Examples:
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:
Examples:
Initialization:
Initialization of Arrays
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:
Example:
Code:
using System;
namespace ArrayApplication {
class MyArray {
int i,j;
n[ i ] = i + 100;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
35
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
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.
};
Syntax:
Code:
using System;
namespace ArrayApplication {
class MyArray {
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
37
int 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
Declaring an array, does not create the array in memory. To create the above array −
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
38
Example:
using System;
namespace ArrayApplication {
class MyArray {
int 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;
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
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
41
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: ");
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
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.
Code:
using System;
namespace CsharpString {
class Test {
// create string
// 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
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
45
Code:
using System;
class HelloWorld
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));
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
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
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
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.
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;
item-name.variabl_name;
Example:
s1.name = “Sam”;
s1.class = 9;
s1.roll = 22;
Code:
using System;
struct Books {
};
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
50
/* book 1 specification */
Book1.book_id = 6495407;
/* book 2 specification */
Book2.book_id = 6495700;
Console.ReadKey();
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
51
Code:
using System;
width = w;
height = h;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
52
r.areaOfRectangle();
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
53
Chapter: 6
Pointer
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
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
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.
using System;
namespace UnsafeCodeApplication
class Program
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
55
unsafe
// {
int* p = &var;
Console.ReadKey();
Output:
Data is: 20
Data is: 20
using System;
namespace UnsafeCodeApplication
class TestPointer
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
56
*p = *q;
*q = temp;
int* x = &var1;
int* y = &var2;
p.swap(x, y);
Console.ReadKey();
Output:
using System;
namespace UnsafeCodeApplication
class TestPointer
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
57
Console.ReadKey();
Output:
Value of list[0] = 10
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
58
Chapter: 7
Working with 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
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
59
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:
// Main Method
static void Main()
{
Connect();
Console.ReadKey();
}
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
60
Output:
Connection Open !
using System;
using System.Data.SqlClient;
namespace Database_Operation
{
class SelectStatement
{
// Main Method
static void Main()
{
Read();
Console.ReadKey();
}
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
61
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
62
cmd.Dispose();
conn.Close();
}
}
}
Output:
1 - C#
2 - C++
Write to database
Code:
using System;
using System.Data.SqlClient;
namespace Database_Operation {
class InsertStatement {
// Main Method
static void Main()
{
Insert();
Console.ReadKey();
}
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
63
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta