43
C#.NET Programming Unit I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# was developed by Anders Hejlsberg and his team during the development of .Net Framework. C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows use of various high-level languages on different computer platforms and architectures The following reasons make C# a widely used professional language: It is a modern, general-purpose programming language It is object oriented. It is component oriented. It is easy to learn. It is a structured language. It produces efficient programs. It can be compiled on a variety of computer platforms. It is a part of .Net Framework. Object Oriented Programming Object-oriented programming (OOP) is the core ingredient of the .NET framework. OOP is so important that, before embarking on the road to .NET, you must understand its basic principles and terminology to write even a simple program. The fundamental idea behind OOP is to combine into a single unit both data and the methods that operate on that data; such units are called an object. All OOP languages provide mechanisms that help you implement the object- oriented model. They are encapsulation, inheritance, polymorphism and reusability.

C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

C#.NET Programming

Unit – I

Overview of c#

C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

and approved by European Computer Manufacturers Association (ECMA) and International

Standards Organization (ISO).

C# was developed by Anders Hejlsberg and his team during the development of .Net

Framework.

C# is designed for Common Language Infrastructure (CLI), which consists of the executable

code and runtime environment that allows use of various high-level languages on different

computer platforms and architectures

The following reasons make C# a widely used professional language:

It is a modern, general-purpose programming language

It is object oriented.

It is component oriented.

It is easy to learn.

It is a structured language.

It produces efficient programs.

It can be compiled on a variety of computer platforms.

It is a part of .Net Framework.

Object Oriented Programming

Object-oriented programming (OOP) is the core ingredient of the .NET framework. OOP is so

important that, before embarking on the road to .NET, you must understand its basic principles

and terminology to write even a simple program. The fundamental idea behind OOP is to

combine into a single unit both data and the methods that operate on that data; such units are

called an object. All OOP languages provide mechanisms that help you implement the object-

oriented model. They are encapsulation, inheritance, polymorphism and reusability.

Page 2: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

Encapsulation

Encapsulation is a programming mechanism that binds together code and the data it manipulates,

and that keeps both safe from outside interference and misuse. In an object oriented language,

code and data can be bound together in such a way that a self-contained black box is created.

Within the box are all necessary data and code. When code and data are linked together in this

fashion, an object is created. In other words, an object is the device that supports encapsulation.

Polymorphism

Polymorphism (from Greek, meaning “many forms”) is the quality that allows one interface to

access a general class of actions. A simple example of polymorphism is found in the steering

wheel of an automobile. The steering wheel (the interface) is the same no matter what type of

actual steering mechanism is used. That is, the steering wheel works the same whether your car

has manual steering, power steering, or rack-and-pinion steering. Thus, turning the steering

wheel left causes the car to go left no matter what type of steering is used. The benefit of the

uniform interface is, of course, that once you know how to operate the steering wheel, you can

drive any type of car.

Inheritance

Inheritance is the process by which one object can acquire the properties of another object. This

is important because it supports the concept of hierarchical classification. If you think about it,

most knowledge is made manageable by hierarchical (that is, top-down) classifications. For

example, a Red Delicious apple is part of the classification apple, which in turn is part of the fruit

class, which is under the larger class food. That is, the food class possesses certain qualities

(edible, nutritious, and so on) which also, logically, apply to its subclass, fruit

A First Simple Program

using System;

class Example

{

// A C# program begins with a call to Main().

Page 3: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

static void Main() {

Console.WriteLine("A simple C# program.");

}

}

DATATYPES , LITERALS AND VARIABLES

C#’s Value Types

C# contains two general categories of built-in data types: value types and reference types. The

difference between the two types is what a variable contains. For a value type, a variable holds

an actual value, such 3.1416 or 212. For a reference type, a variable holds a reference to the

value.

Integers

C# defines nine integer types: char, byte, sbyte, short, ushort, int, uint, long, and ulong.

However, the char type is primarily used for representing characters. The remaining eight integer

types are used for numeric calculations.

Page 4: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

Example:

using System;

class Use_byte {

static void Main() {

byte x;

int sum;

sum = 0;

for(x = 1; x <= 100; x++)

sum = sum + x;

Console.WriteLine("Summation of 100 is " + sum);

}}

Output

Summation of 100 is 5050

Floating-Point Types

The floating-point types can represent numbers that have fractional components. There are two

kinds of floating-point types, float and double, which represent single- and double precision

numbers, respectively. The type float is 32 bits wide and has an approximate range of 1.5E–45 to

3.4E+38. The double type is 64 bits wide and has an approximate range of 5E–324 to 1.7E+308.

Example

using System;

class FindRadius {

static void Main() {

Double r;

Double area;

area = 10.0;

r = Math.Sqrt(area / 3.1416);

Console.WriteLine("Radius is " + r);

Page 5: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

} }

Output

Radius is 1.78412203012729

Characters

In C#, characters are not 8-bit quantities like they are in many other computer languages, such as

C++. Instead, C# uses a 16-bit character type called Unicode. Unicode defines a character set

that is large enough to represent all of the characters found in all human languages. In C#, char is

an unsigned 16-bit type having a range of 0 to 65,535. The standard 8-bit ASCII character set is a

subset of Unicode and ranges from 0 to 127. Thus, the ASCII characters are still valid C#

characters.

Example

char ch;

ch = 'X';

Console.writeline(“the value of ch:”+ch);

Although char is defined by C# as an integer type, it cannot be freely mixed with integers in all

cases. This is because there are no automatic type conversions from integer to char.

For example, the following fragment is invalid:

char ch;

ch = 88; // error, won't work

The bool Type

The bool type represents true/false values. C# defines the values true and false using the reserved

words true and false. Thus, a variable or expression of type bool will be one of these two values.

Furthermore, there is no conversion defined between bool and integer values. For example, 1

does not convert to true, and 0 does not convert to false.

Example

Page 6: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

// Demonstrate bool values.

using System;

class BoolDemo {

static void Main() {

bool b;

b = false;

Console.WriteLine("b is " + b);

b = true;

Console.WriteLine("b is " + b);

// A bool value can control the if statement.

if(b) Console.WriteLine("This is executed.");

b = false;

if(b) Console.WriteLine("This is not executed.");

// Outcome of a relational operator is a bool value.

Console.WriteLine("10 > 9 is " + (10 > 9));

}

}

Output

b is False

b is True

This is executed.

10 > 9 is True

Literals

In C#, literals refer to fixed values that are represented in their human-readable form.

For example, the number 100 is a literal. For the most part, literals and their usage are so

intuitive that they have been used in one form or another by all the preceding sample programs

Page 7: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

C# literals can be of any simple type. The way each literal is represented depends upon its type.

As explained earlier, character literals are enclosed between single quotes. For example, „a‟ and

„%‟ are both character literals.

Hexadecimal Literals

The base 16 number system is called hexadecimal and uses the digits 0 through 9 plus the letters

A through F, which stand for 10, 11, 12, 13, 14, and 15. For example, the hexadecimal number

10 is 16 in decimal. Because of the frequency with which hexadecimal numbers are used, C#

allows you to specify integer literals in hexadecimal format.

count = 0xFF; // 255 in decimal

incr = 0x1a; // 26 in decimal

Character Escape Sequences

Enclosing character literals in single quotes works for most printing characters, but a few

characters, such as the carriage return, pose a special problem when a text editor is used. In

addition, certain other characters, such as the single and double quotes, have special meaning in

C#, so you cannot use them directly.

Example

ch = '\t';

String Literals

C# supports one other type of literal: the string. A string literal is a set of characters enclosed by

double quotes. For example,

Page 8: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

"this is a test"

is a string. You have seen examples of strings in many of the WriteLine( ) statements in the

preceding sample programs.

In addition to normal characters, a string literal can also contain one or more of the escape

sequences just described. For example, consider the following program. It uses the \n and \t

escape sequences.

Example

using System;

class StrDemo {

static void Main() {

Console.WriteLine("Line One\nLine Two\nLine Three");

Console.WriteLine("One\tTwo\tThree");

Console.WriteLine("Four\tFive\tSix");

// Embed quotes.

Console.WriteLine("\"Why?\", he asked.");

}

}

Output

Line One

Line Two

Line Three

One Two Three

Four Five Six

Page 9: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

"Why?", he asked.

VARIABLES

Variables are declared using this form of statement:

type var-name;

where type is the data type of the variable and var-name is its name. You can declare a variable

of any valid type, including the value types just described. It is important to understand that a

variable‟s capabilities are determined by its type. For example, a variable of type bool cannot be

used to store floating-point values. Furthermore, the type of a variable cannot change during its

lifetime. An int variable cannot turn into a char variable.

Initializing a Variable

The general form of initialization,

type var-name = value;

Here, value is the value that is given to the variable when it is created. The value must be

compatible with the specified type.

Here are some examples:

int count = 10; // give count an initial value of 10

char ch = 'X'; // initialize ch with the letter X

float f = 1.2F; // f is initialized with 1.2

When declaring two or more variables of the same type using a comma-separated list, you can

give one or more of those variables an initial value. For example:

int a, b = 8, c = 19, d; // b and c have initializations

Dynamic Initialization

C# allows variables to be initialized dynamically, using any expression valid at the point at

which the variable is declared.

Page 10: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

Example

using System;

class DynInit {

static void Main() {

// Length of sides.

double s1 = 4.0;

double s2 = 5.0;

// Dynamically initialize hypot.

double hypot = Math.Sqrt( (s1 * s1) + (s2 * s2) );

Console.Write("Hypotenuse of triangle with sides " +

s1 + " by " + s2 + " is ");

Console.WriteLine("{0:#.###}.", hypot);

}

}

Output

Hypotenuse of triangle with sides 4 by 5 is 6.403.

The Scope and Lifetime of Variables

C# allows a local variable to be declared within any block. a block begins with an opening curly

brace and ends with a closing curlybrace. A block defines a scope. Thus, each time you start a

new block, you are creating a new scope. The scope defined by a method begins with its opening

curly brace and ends with its closing curly brace.

Scopes can be nested. For example, each time you create a block of code, you are creating a new,

nested scope. When this occurs, the outer scope encloses the inner scope. This means that local

variables declared in the outer scope will be visible to code within the inner scope.

Example

using System;

class ScopeDemo {

Page 11: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

static void Main() {

int x; // known to all code within Main()

x = 10;

if(x == 10) { // start new scope

int y = 20; // known only to this block

// x and y both known here.

Console.WriteLine("x and y: " + x + " " + y);

x = y * 2;

}

// y = 100; // Error! y not known here.

// x is still known here.

Console.WriteLine("x is " + x);

}

}

TYPE CONVERSION AND CASTING

In programming, it is common to assign one type of variable to another. For example, you might

want to assign an int value to a float variable, as shown here:

int i;

float f;

i = 10;

f = i; // assign an int to a float

When compatible types are mixed in an assignment, the value of the right side is automatically

converted to the type of the left side. Thus, in the preceding fragment, the value in i is converted

Page 12: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

into a float and then assigned to f. However, because of C#‟s strict type-checking, not all types

are compatible, and thus, not all type conversions are implicitly allowed.

Automatic Conversions

When one type of data is assigned to another type of variable, an implicit type conversion will

take place automatically if

The two types are compatible.

The destination type has a range that is greater than the source type.

Example

using System;

class LtoD {

static void Main() {

long L;

double D;

L = 100123285L;

D = L;

Console.WriteLine("L and D: " + L + " " + D);

}

}

Casting Incompatible Types

A cast is an instruction to the compiler to convert theoutcome of an expression into a specified

type. Thus, it requests an explicit type conversion.

A cast has this general form:

(target-type) expression

Here, target-type specifies the desired type to convert the specified expression to. Forexample,

Page 13: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

double x, y;

if you want the type of the expression x/y to be int, you can write

(int) (x / y)

Example

x = 10.0;

y = 3.0;

// Cast double to int, fractional component lost.

i = (int) (x / y);

Console.WriteLine("Integer outcome of x / y: " + i);

Type Conversion in Expressions

In an expression, you can freely mix two or more different types of data as long as they are

compatible with each other. For example, you can mix short and long within an expression

because they are both numeric types. When different types of data are mixed within an

expression, they are converted to the same type, on an operation-by-operation basis.

Example

using System;

class PromDemo {

static void Main() {

byte b;

b = 10;

b = (byte) (b * b); // cast needed!!

Console.WriteLine("b: "+ b);

}

Page 14: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

}

Using Casts in Expressions

A cast can be applied to a specific portion of a larger expression. This gives you fine-grained

control over the way type conversions occur when an expression is evaluated. For example,

consider the following program.

Example

using System;

class CastExpr {

static void Main() {

double n;

for(n = 1; n <= 3; n++) {

Console.WriteLine("The square root of {0} is {1}",

n, Math.Sqrt(n));

Console.WriteLine("Whole number part: {0}" ,

(int) Math.Sqrt(n));

Console.WriteLine("Fractional part: {0}",

Math.Sqrt(n) - (int) Math.Sqrt(n) );

Console.WriteLine();

}

}

}

Output

The square root of 1 is 1

Page 15: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

Whole number part: 1

Fractional part: 0

The square root of 2 is 1.4142135623731

Whole number part: 1

Fractional part: 0.414213562373095

The square root of 3 is 1.73205080756888

Whole number part: 1

Fractional part: 0.732050807568877

Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical

manipulations. C# has rich set of built-in operators and provides the following type of operators:

Arithmetic Operators

Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Misc Operators

Arithmetic Operators

Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10

and variable B holds 20 then:

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 A-- = 9

Page 16: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

by one

Example

using System;

namespace OperatorsAppl

{

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;

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();

}

Page 17: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

}

}

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

Relational Operators

Following table shows all the relational operators supported by C#. Assume variable A holds 10

and variable B holds 20, then:

Operator Description Example

== Checks if the values of two operands are equal or not, if yes

then condition becomes true.

(A == B) is not

true.

!= Checks if the values of two operands are equal or not, if

values are not equal then condition becomes true.

(A != B) is true.

> Checks if the value of left operand is greater than the value of

right operand, if yes then condition becomes true.

(A > B) is not

true.

< Checks if the value of left operand is less than the value of

right operand, if yes then condition becomes true.

(A < B) is true.

>= Checks if the value of left operand is greater than or equal to

the value of right operand, if yes then condition becomes true.

(A >= B) is not

true.

<= Checks if the value of left operand is less than or equal to the

value of right operand, if yes then condition becomes true.

(A <= B) is

true.

Example

using System;

class Program

{

static void Main(string[] args)

{

int a = 21;

int b = 10;

Page 18: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

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)

Page 19: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

{

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

Logical Operators

Following table shows all the logical operators supported by C#. Assume variable A holds

Boolean value true and variable B holds Boolean value false, then:

Operator Description Example

&& Called Logical AND operator. If both the operands are

non zero then condition becomes true.

(A && B) is false.

|| Called Logical OR Operator. If any of the two operands is

non zero then condition becomes true.

(A || B) is true.

! Called Logical NOT Operator. Use to reverses the logical

state of its operand. If a condition is true then Logical

NOT operator will make false.

!(A && B) is true.

Example

using System;

namespace OperatorsAppl

{

class Program

{

Page 20: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

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();

Page 21: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

}

}

}

Output

Line 1 - Condition is true

Line 2 - Condition is true

Line 3 - Condition is not true

Line 4 - Condition is true

Bitwise Operators

Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^

are as follows:

p q p & q p | q p ^ q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13, then in the binary format they are as follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C# are listed in the following table. Assume variable A holds

60 and variable B holds 13, then:

Operator Description Example

& Binary AND Operator copies a bit to the result if it

exists in both operands.

(A & B) = 12, which

is 0000 1100

| Binary OR Operator copies a bit if it exists in

either operand.

(A | B) = 61, which is

0011 1101

^ Binary XOR Operator copies the bit if it is set in

one operand but not both.

(A ^ B) = 49, which is

0011 0001

Page 22: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

~ Binary Ones Complement Operator is unary and

has the effect of 'flipping' bits.

(~A ) = 61, which is

1100 0011 in 2's

complement due to a

signed binary number.

<< Binary Left Shift Operator. The left operands

value is moved left by the number of bits specified

by the right operand.

A << 2 = 240, which

is 1111 0000

>> Binary Right Shift Operator. The left operands

value is moved right by the number of bits

specified by the right operand.

A >> 2 = 15, which is

0000 1111

Example

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 */

Page 23: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

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

Assignment Operators

There are following assignment operators supported by C#:

Operator Description Example

= Simple assignment operator, Assigns values

from right side operands to left side operand

C = A + B assigns value of A

+ B into C

+= Add AND assignment operator, It adds right

operand to the left operand and assign the result

to left operand

C += A is equivalent to C =

C + A

-= Subtract AND assignment operator, It subtracts

right operand from the left operand and assign

the result to left operand

C -= A is equivalent to C = C

– A

*= Multiply AND assignment operator, It

multiplies right operand with the left operand

and assign the result to left operand

C *= A is equivalent to C = C

* A

/= Divide AND assignment operator, It divides left

operand with the right operand and assign the

result to left operand

C /= A is equivalent to C = C

/ A

%= Modulus AND assignment operator, It takes

modulus using two operands and assign the

result to left operand

C %= A is equivalent to C =

C % A

<<= 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

Page 24: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Example

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

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

Page 25: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

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

Miscellaneous Operators

There are few other important operators including sizeof, typeof and ? : supported by C#

Operator Description Example

sizeof() Returns the size of a data sizeof(int), returns 4.

Page 26: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

type.

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 certain type.

If( Ford is Car) // checks if

Ford is an object of the Car

class.

as Cast without raising an

exception if the cast fails.

Object obj = new

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

Page 27: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

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

Decision Making

Decision making structures requires the programmer to specify one or more conditions to be

evaluated or tested by the program, along with a statement or statements to be executed if the

condition is determined to be true, and optionally, other statements to be executed if the

condition is determined to be false.

Statement Description

if statement An if statement consists of a boolean expression followed by one

or more statements.

if...else statement An if statement can be followed by an optional else statement,

which executes when the boolean expression is false.

nested if statements You can use one if or else if statement inside another if or else if

statement(s).

switch statement A switch statement allows a variable to be tested for equality

against a list of values.

nested switch statements You can use one switch statement inside another switch

statement(s).

if Statement

An if statement consists of a boolean expression followed by one or more statements.

Syntax

The syntax of an if statement in C# is:

if(boolean_expression)

Page 28: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

{

/* statement(s) will execute if the boolean expression is true */

}

If the boolean expression evaluates to true, then the block of code inside the if statement is

executed. If boolean expression evaluates to false, then the first set of code after the end of the if

statement (after the closing curly brace) is executed.

Example

using System;

namespace DecisionMaking

{

class Program

{

static void Main(string[] args)

{

/* local variable definition */

int a = 10;

/* check the boolean condition using if statement */

if (a < 20)

{

/* if condition is true then print the following */

Console.WriteLine("a is less than 20");

}

Console.WriteLine("value of a is : {0}", a);

Console.ReadLine();

}

}

}

Output

Page 29: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

a is less than 20;

value of a is : 10

if...else Statement

An if statement can be followed by an optional else statement, which executes when the boolean

expression is false.

Syntax

The syntax of an if...else statement in C# is:

if(boolean_expression)

{

/* statement(s) will execute if the boolean expression is true */

}

else

{

/* statement(s) will execute if the boolean expression is false */

}

If the boolean expression evaluates to true, then the if block of code is executed, otherwise else

block of code is executed.

Example

using System;

namespace DecisionMaking

{

class Program

{

static void Main(string[] args)

{

/* local variable definition */

int a = 100;

/* check the boolean condition */

if (a < 20)

Page 30: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

{

/* if condition is true then print the following */

Console.WriteLine("a is less than 20");

}

else

{

/* if condition is false then print the following */

Console.WriteLine("a is not less than 20");

}

Console.WriteLine("value of a is : {0}", a);

Console.ReadLine();

}

}

}

Output

a is not less than 20;

value of a is : 100

The if...else if...else Statement

An if statement can be followed by an optional else if...else statement, which is very useful to

test various conditions using single if...else if statement.

When using if, else if and else statements there are few points to keep in mind.

An if can have zero or one else's and it must come after any else if's.

An if can have zero to many else if's and they must come before the else.

Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax

The syntax of an if...else if...else statement in C# is:

if(boolean_expression 1)

{

/* Executes when the boolean expression 1 is true */

Page 31: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

}

else if( boolean_expression 2)

{

/* Executes when the boolean expression 2 is true */

}

else if( boolean_expression 3)

{

/* Executes when the boolean expression 3 is true */

}

else

{

/* executes when the none of the above condition is true */

}

Example

using System;

namespace DecisionMaking

{

class Program

{

static void Main(string[] args)

{

/* local variable definition */

int a = 100;

/* check the boolean condition */

if (a == 10)

{

/* if condition is true then print the following */

Console.WriteLine("Value of a is 10");

Page 32: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

}

else if (a == 20)

{

/* if else if condition is true */

Console.WriteLine("Value of a is 20");

}

else if (a == 30)

{

/* if else if condition is true */

Console.WriteLine("Value of a is 30");

}

else

{

/* if none of the conditions is true */

Console.WriteLine("None of the values is matching");

}

Console.WriteLine("Exact value of a is: {0}", a);

Console.ReadLine();

}

}

}

Output

None of the values is matching

Exact value of a is: 100

Nested if Statements

It is always legal in C# to nest if-else statements, which means you can use one if or else if

statement inside another if or else if statement(s).

Syntax

The syntax for a nested if statement is as follows:

Page 33: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

if( boolean_expression 1)

{

/* Executes when the boolean expression 1 is true */

if(boolean_expression 2)

{

/* Executes when the boolean expression 2 is true */

}

}

Example

using System;

namespace DecisionMaking

{

class Program

{

static void Main(string[] args)

{

//* local variable definition */

int a = 100;

int b = 200;

/* check the boolean condition */

if (a == 100)

{

/* if condition is true then check the following */

if (b == 200)

{

/* if condition is true then print the following */

Console.WriteLine("Value of a is 100 and b is 200");

}

Page 34: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

}

Console.WriteLine("Exact value of a is : {0}", a);

Console.WriteLine("Exact value of b is : {0}", b);

Console.ReadLine();

}

}

}

Output

Value of a is 100 and b is 200

Exact value of a is : 100

Exact value of b is : 200

Switch Statement

A switch statement allows a variable to be tested for equality against a list of values. Each value

is called a case, and the variable being switched on is checked for each switch case.

Syntax

The syntax for a switch statement in C# is as follows:

switch(expression){

case constant-expression :

statement(s);

break; /* optional */

case constant-expression :

statement(s);

break; /* optional */

/* you can have any number of case statements */

default : /* Optional */

statement(s);

}

The following rules apply to a switch statement:

Page 35: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

The expression used in a switch statement must have an integral or enumerated type, or

be of a class type in which the class has a single conversion function to an integral or

enumerated type.

You can have any number of case statements within a switch. Each case is followed by

the value to be compared to and a colon.

The constant-expression for a case must be the same data type as the variable in the

switch, and it must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that case

will execute until a break statement is reached.

When a break statement is reached, the switch terminates, and the flow of control jumps

to the next line following the switch statement.

Not every case needs to contain a break. If no break appears, the flow of control will fall

through to subsequent cases until a break is reached.

A switch statement can have an optional default case, which must appear at the end of the

switch. The default case can be used for performing a task when none of the cases is true.

No break is needed in the default case.

Example

using System;

namespace DecisionMaking

{

class Program

{

static void Main(string[] args)

{

/* local variable definition */

char grade = 'B';

switch (grade)

{

case 'A':

Console.WriteLine("Excellent!");

break;

case 'B':

case 'C':

Page 36: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

Console.WriteLine("Well done");

break;

case 'D':

Console.WriteLine("You passed");

break;

case 'F':

Console.WriteLine("Better try again");

break;

default:

Console.WriteLine("Invalid grade");

break;

}

Console.WriteLine("Your grade is {0}", grade);

Console.ReadLine();

}

}

}

Output

Well done

Your grade is B

Loops

A loop statement allows us to execute a statement or a group of statements multiple times and

following is the general from of a loop statement in most of the programming languages.

C# provides following types of loop to handle looping requirements. Click the following links to

check their detail.

Loop Type Description

while loop It repeats a statement or a group of statements

while a given condition is true. It tests the

condition before executing the loop body.

for loop It executes a sequence of statements multiple

times and abbreviates the code that manages

Page 37: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

the loop variable.

do...while loop It is similar to a while statement, except that

it tests the condition at the end of the loop

body

nested loops You can use one or more loops inside any

another while, for or do..while loop.

While Loop

A while loop statement in C# repeatedly executes a target statement as long as a given condition

is true.

Syntax

The syntax of a while loop in C# is:

while(condition)

{

statement(s);

}

Here, statement(s) may be a single statement or a block of statements. The condition may be any

expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the

loop.

Example

using System;

namespace Loops

{

class Program

{

static void Main(string[] args)

{

/* local variable definition */

int a = 10;

/* while loop execution */

while (a < 20)

{

Page 38: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

Console.WriteLine("value of a: {0}", a);

a++;

}

Console.ReadLine();

}

}

}

For Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to

execute a specific number of times.

Syntax

The syntax of a for loop in C# is:

for ( init; condition; increment )

{

statement(s);

}

Here is the flow of control in a for loop:

1. The init step is executed first, and only once. This step allows you to declare and initialize any

loop control variables. You are not required to put a statement here, as long as a semicolon

appears.

2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the

body of the loop does not execute and flow of control jumps to the next statement just after the

for loop.

3. After the body of the for loop executes, the flow of control jumps back up to the increment

statement. This statement allows you to update any loop control variables. This statement can be

left blank, as long as a semicolon appears after the condition.

4. The condition is now evaluated again. If it is true, the loop executes and the process repeats

itself (body of loop, then increment step, and then again testing for a condition). After the

condition becomes false, the for loop terminates.

Example

Page 39: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

using System;

namespace Loops

{

class Program

{

static void Main(string[] args)

{

/* for loop execution */

for (int a = 10; a < 20; a = a + 1)

{

Console.WriteLine("value of a: {0}", a);

}

Console.ReadLine();

}

}

}

Do...While Loop

Unlike for and while loops, which test the loop condition at the start of the loop, the do...while

loop checks its condition at the end of the loop.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute

at least one time.

Syntax

The syntax of a do...while loop in C# is:

do

{

statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the

loop execute once before the condition is tested.

Page 40: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop

execute again. This process repeats until the given condition becomes false.

Example:

using System;

namespace Loops

{

class Program

{

static void Main(string[] args)

{

/* local variable definition */

int a = 10;

/* do loop execution */

do

{

Console.WriteLine("value of a: {0}", a);

a = a + 1;

} while (a < 20);

Console.ReadLine();

}

}

}

Nested Loops

C# allows to use one loop inside another loop. Following section shows few examples to

illustrate the concept.

Syntax

The syntax for a nested for loop statement in C# is as follows:

for ( init; condition; increment )

{

Page 41: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

for ( init; condition; increment )

{

statement(s);

}

statement(s);

}

Example

using System;

namespace Loops

{

class Program

{

static void Main(string[] args)

{

/* local variable definition */

int i, j;

for (i = 2; i < 100; i++)

{

for (j = 2; j <= (i / j); j++)

if ((i % j) == 0) break; // if factor found, not prime

if (j > (i / j))

Console.WriteLine("{0} is prime", i);

}

Console.ReadLine();

}

}

}

Goto

Page 42: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

The goto requires a label for operation. A label is a valid C# identifier followed by a colon. The

label must be in the same method as the goto that uses it and within scope. For example, a loop

from 1 to 100 could be written using a goto and a label.

Example

using System;

class SwitchGoto {

static void Main() {

for(int i=1; i < 5; i++) {

switch(i) {

case 1:

Console.WriteLine("In case 1");

goto case 3;

case 2:

Console.WriteLine("In case 2");

goto case 1;

case 3:

Console.WriteLine("In case 3");

goto default;

default:

Console.WriteLine("In default");

break;

}

Console.WriteLine();

Page 43: C#.NET Programming Unit I Overview of c# · C#.NET Programming Unit – I Overview of c# C# is a modern, general-purpose, object-oriented programming language developed by Microsoft

}

// goto case 1; // Error! Can't jump into a switch.

}

}

Output

In case 1

In case 3

In default

In case 2

In case 1

In case 3

In default