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

Unit 2 Notes11

Uploaded by

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

Unit 2 Notes11

Uploaded by

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

Unit 2: Introduction to C#

What is C#?
C# is pronounced as "C-Sharp". It is an object-oriented programming
language provided by Microsoft that runs on .Net Framework.

By the help of C# programming language, we can develop different types


of secured and robust applications:

 Window applications
 Web applications
 Distributed applications
 Web service applications
 Database applications etc.
The following are the reasons for making C# widely used language
 It is component oriented.
 It is modern, general purpose programming language.
 It is object-oriented language.
 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.

C# is approved as a standard by European Computer Manufacturers


Association (ECMA) and International Standards Organization
(ISO). Common Language Infrastructure(CLI) is a specification that
describes executable code and runtime environment.
C# programming language is influenced by C++, Java, Eiffel, Modula-3,
Pascal etc. languages.
Features of C#
 Simple
 Modern programming language
 Object oriented
 Type safe
 Interoperability
 Scalable and Updateable
 Component oriented
 Structured programming language
 Rich Library
 Fast speed

1) Simple
C# is a simple language in the sense that it provides structured approach
(to break the problem into parts), rich set of library functions, data types
etc.
2) Modern Programming Language
C# programming is based upon the current trend and it is very powerful
and simple for building scalable, interoperable and robust applications.
3) Object Oriented
C# is object oriented programming language. OOPs makes development
and maintenance easier where as in Procedure-oriented programming
language it is not easy to manage if code grows as project size grow.
4) Type Safe
C# type safe code can only access the memory location that it has
permission to execute. Therefore it improves a security of the program.
5) Interoperability
Interoperability process enables the C# programs to do almost anything
that a native C++ application can do.
6) Scalable and Updateable
C# is automatic scalable and updateable programming language. For
updating our application we delete the old files and update them with new
ones.

7) Component Oriented
C# is component oriented programming language. It is the predominant
software development methodology used to develop more robust and
highly scalable applications.
8) Structured Programming Language
C# is a structured programming language in the sense that we can break
the program into parts using functions. So, it is easy to understand and
modify.
9) Rich Library
C# provides a lot of inbuilt functions that makes the development fast.
10) Fast Speed
The compilation and execution time of C# language is fast.

Structure of C# program
 Using is the keyword used to fetch all the methods which are there in the
program. Declaring namespace using the "namespace" keyword.
 Declaring a class using the keyword "class".
 Class members and attributes.
 The Main() method.
 Other statements and expressions.
 Writing comments for user understanding and non-executable
statements.
Example
using System;
namespace printHelloCsharp
{
class HelloCsharp
{
static void Main(string[] args)
{
/* Print some string in C# */

Console.WriteLine("HelloC#.");
Console.ReadKey();
}
}

/* Comments */ /* Print, some string in C# */, is


the comment statement that does
not get executed by the compiler
and is used for code readers or
programmers' understanding.
Using Here, using keyword is employed
for fetching all the associated
methods that are within the
System namespace. Any C#
program can have multiple using
statements.
namespace This next statement is used for
declaring a namespace, which is a
collection of classes under asingle
unit; here, "printHelloCsharp".
class Next, you have declared a class
"HelloCsharp" using the keyword
class, which is used for preserving
theconcept of encapsulation.
Main() Inside a class, you can have
multiple methods and declaring
variable names. The static/void is a
return value, which will be
explained in a while.
Console.WriteLine() Console.WriteLine() is a predefined
method used fordisplaying any
string or variable's value in a C#
program.
Console.ReadLine() Console.ReadKey() is another
predefined method used to make
the program wait for any key-
press.

C# literals
The fixed values are called literals. The constants refer to fixed values
that the program may not alter during its execution.
Constants can be of any of the basic data types like an integer
constant, a floating constant, a character constant, or a string
literal. There are also enumeration constants as well.

Some of the literals in C# are


1) Integer Literals
An integer literal can be a decimal, or hexadecimal constant. A prefix
specifies the base.
Here are some example of Integer Literals −
20 // int
30u // unsigned int
30l // long
2) Float Literals
A floating-point literal has an integer part, a decimal point, a fractional
part, and an exponent part. You can represent floating point literals either
in decimal form or exponential form.
Here are some examples of Float Literals −
2.64734
314159E-F5

3) String Literals
String literals or constants are enclosed in double quotes "" or with @"". A
string contains characters that are similar to character literals: plain
characters, escape sequences, and universal characters.
Here are some examples of String Literals −
“Hello,
World"\
Variables
Variables are containers for storing data values.
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
type variableName=value;
Example:
String str=”AESNC”

In C#, there are different types of variables (defined with different


keywords), for example:
 int - stores integers (whole numbers), without decimals, such as
123 or -123
 double - stores floating point numbers, with decimals, such as
19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 string - stores text, such as "Hello World". String values are
surrounded by double quotes
 bool - stores values with two states: true or false

Rules for defining variables


 A variable can have alphabets, digits and underscore.
 A variable name can start with alphabet and underscore only. It
can't start with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g.
char, float etc.

Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by
a constant expression.
The general form of initialization is
variable_name = value;

Some examples are −


1. int d = 3, f = 5; /* initializing d and
f.

2. */byte z = 22; /* initializes z. */


3. double pi = 3.14159; /* declares an approximation of
pi.
4. */char x = 'x'; /* the variable x has the value 'x'.
Example:
Using System;
Namespace VariableDef
{
Class Program
{
Static void Main(string[] args)
{
short a; /*variable declaration
int b; /*variable declaration
double c; /*variable declaration
/*actual initialization*/
a=10;
b=20;
c=a+b;
Console.WriteLine(“a={0},b={1},c={2}”, a,b,c);
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following
result −
a = 10, b = 20, c = 30

Types of variable
There are 3 types of variable
1. Local variable
2. static variable or class variable
3. Instance variable or non-static variable

1.Local Variable
A variable defined within a block or method or constructor is called local
variable.
 These variables are created when the block is entered or the
function is called and destroyed after exiting from the block or when
the call returns from the function.
 The scope of the variable exists only within the block in which it is
declared. i.e we can access these variables only within that block. 
xample:
using System;
namespace ClassDetails

{
// Method
public void StudentAge()
{
// local variable age
int age = 0;
age = age + 10;
Console.WriteLine("Student age is : " + age);
}
// Main Method
public static void Main(String[] args)
{
// Creating object
StudentDetails obj = new StudentDetails();
// calling the function
obj.StudentAge();
}
}
Output:
Student age is : 10
2.Instance variables
 Instance variable are non-static variables and are declared in a
class but outside any method, constructor or block.
 As instance variables are declared in a class, these variables are
created when an object of the class is created and destroyed when
the object is destroyed.
Example:
using System;
class Marks
{
// These variables are instance variables.
int engMarks;
int mathsMarks;
int phyMarks;

// Main Method
public static void Main(String[] args)
{
// first object
Marks obj1 = new Marks();
obj1.engMarks = 90;
obj1.mathsMarks = 80;
obj1.phyMarks = 93;

// second object
Marks obj2 = new Marks();
obj2.engMarks = 95;
obj2.mathsMarks = 70;
obj2.phyMarks = 90;

// displaying marks for first object


Console.WriteLine("Marks for first object:");
Console.WriteLine(obj1.engMarks);
Console.WriteLine(obj1.mathsMarks);
Console.WriteLine(obj1.phyMarks);

// displaying marks for second object


Console.WriteLine("Marks for second object:");
Console.WriteLine(obj2.engMarks);
Console.WriteLine(obj2.mathsMarks);
Console.WriteLine(obj2.phyMarks);
}
}

Output :

Marks for first object:


90
80
93

Marks for second object:

95

70

90
1. Static variables
Static variable are also known as Class variables. If a variable is explicitly
declared with the static modifier or if a variable is declared under any
static block then these variables are known as static variables.
Example
using System;
class Emp
{
// static variable salary
static double salary;
static String name = "Hani";

// Main Method
public static void Main(String[] args)
{
// accessing static variable
// without object
Emp.salary = 100000;
Console.WriteLine(Emp.name + "'s average salary:"+ Emp.salary);

}
}

Output:
Hani average salary:100000

Constants
If a variable is declared by using the keyword “const” then it as a
constant variable and these constant variables can’t be modified once
after their declaration, so it’s must initialize at the time of declaration
only.
Example
using System;
class Program
{
// constant variable
const float max = 50;
// Main Method
public static void Main()
{
// creating object
Program obj = new Program();
// displaying result
Console.WriteLine("The value of max is = " + Program.max);
}
}
Output:
The value of max is = 50

C# Data Types
The variables in C#, are categorized into the following types −
 Value types
 Reference types
 Pointer types
a) Value Type:
A data type specifies the type of data that a variable can store such as
integer, floating, character etc.
A data type specifies the size and type of variable values.

Data Type Size Description


Stores whole numbers from -2,147,483,648 to
Int 4 bytes
2,147,483,647
Stores whole numbers from -
Long 8 bytes 9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Stores fractional numbers. Sufficient for storing 6
Float 4 bytes
to 7 decimal digits
Stores fractional numbers. Sufficient for storing
Double 8 bytes
15 decimal digits
Bool 1 bit Stores true or false values
Stores a single character/letter, surrounded by
Char 2 bytes
single quotes
2 bytes per
String Stores a sequence
character

Integer Types
1)Int
The int data type is the preferred data type when we create variables
with a numeric value.
Example
int a = 10;
Console.WriteLine(a);

Long
The long data type can store whole numbers from -

Example
long myNum = 15000000000L;
Console.WriteLine(myNum);

Floating Point Types


You should use a floating point type whenever you need a number with a
decimal, such as 9.99 or 3.14515.
The float and double data types can store fractional numbers.
float myNum = 5.75F;
Console.WriteLine(myNum);
double myNum = 19.99D;
Console.WriteLine(myNum);
1) Scientific Numbers
A floating point number can also be a scientific number with an "e" to
indicate the power of 10:

Example

Float f1=35eeF;

Double d1=12E4D;

Console.WriteLine(f1);

Console.WriteLine(d1);

2) Booleans
A boolean data type is declared with the bool keyword and can only take
the values true or false:

Example
bool a = true;
bool b = false;
Console.WriteLine(a); // Outputs True
Console.WriteLine(b); // Outputs False

Boolean values are mostly used for conditional testing.

3) 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 grade = 'B';
Console.WriteLine(grade);

4) 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);
2) Reference Type
The reference types do not contain the actual data stored in a variable,
but they contain a reference to the variables. They refer to a memory
location.
Example of built-in reference types are: object, dynamic, and string.

a) Object Type
It is the ultimate base class for all data types in C# Common Type
System (CTS).
Object is an alias for System.Object class.
The object types can be assigned values of any other types, value
types, reference types, predefined or user-defined types.
However, before assigning values, it needs type conversion.

Example:
object obj;
obj = 100; // this is boxing

b) Dynamic Type
You can store any type of value in the dynamic data type variable. Type
checking for these types of variables takes place at run-time.

Syntax for declaring a dynamic type is −


dynamic <variable_name> = value;

example,
dynamic d = 20;
C) String Type
The String Type allows you to assign any string values to a variable. The
string type is an alias for the System.String class. It is derived from
object type.
The value for a string type can be assigned using string literals in two
forms: quoted and @quoted.
For example,
String str = "Tutorials Point";
A @quoted string literal looks as follows −
@"Ttorials Point"

3) Pointer Type
Pointer type variables store the memory address of another type. Pointers
in C# have the same capabilities as the pointers in C or C++.
Syntax for declaring a pointer type is −
type* identifier;

For example
char* cptr;
int* iptr;

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
 Miscellaneous Operators
Arithmetic Operators

Following table shows all the arithmetic operators supported by C#.

Operator Description Example

+ Adds two operands A + B = 30

Subtracts second operand from the


- A - B = -10
first

* Multiplies both operands A * B = 200

/ Divides numerator by de-numerator B/A=2


Modulus Operator and remainder of
% B%A=0
after an integer division

Increment operator increases integer


++ A++ = 11
value by one

Decrement operator decreases integer


-- A-- = 9
value by one

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 (A == B) is not true.
becomes true.

Checks if the values of two operands are


!= equal or not, if values are not equal then (A != B) is true.
condition becomes true.

Checks if the value of left operand is


> greater than the value of right operand, (A > B) is not true.
if yes then condition becomes true.

Checks if the value of left operand is less


< than the value of right operand, if yes (A < B) is true.
then condition becomes true.

Checks if the value of left operand is


greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition
becomes true.

Checks if the value of left operand is less


than or equal to the value of right
<= (A <= B) is true.
operand, if yes then condition becomes
true.

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 (A && B) is false.
condition becomes true.

Called Logical OR Operator. If any of


|| the two operands is non zero then (A || B) is true.
condition becomes true.

Called Logical NOT Operator. Use to


reverses the logical state of its
! !(A && B) is true.
operand. If a condition is true then
Logical NOT operator will make false.

Bitwise Operators

Bitwise operator works on bits and perform bit by bit operation. The truth
tables for &, |, and ^.
Operator Description Example
Binary AND Operator copies a bit to the (A & B) = 12, which is
&
result if it exists in both operands. 0000 1100
Binary OR Operator copies a bit if it exists (A | B) = 61, which is
|
in either operand. 0011 1101
Binary XOR Operator copies the bit if it is (A ^ B) = 49, which is
^
set in one operand but not both. 0011 0001
(~A ) = -61, which is
Binary Ones Complement Operator 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
operands value is moved left by the A << 2 = 240, which is
<<
number of bits specified by the right 1111 0000
operand.
Binary Right Shift Operator. The left
operands value is moved right by the A >> 2 = 15, which is
>>
number of bits specified by the right 0000 1111
operand.
Example

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

Assignment Operators

There are following assignment operators supported by C# −

Operator Description Example

Simple assignment
operator, Assigns values C = A + B assigns value of A + B
=
from right side operands into C
to left side operand

Add AND assignment


operator, It adds right
+= operand to the left C += A is equivalent to C = C + A
operand and assign the
result to left operand

Subtract AND assignment


operator, It subtracts right
-= operand from the left C -= A is equivalent to C = C - A
operand and assign the
result to left operand

Multiply AND assignment


operator, It multiplies right
*= operand with the left C *= A is equivalent to C = C * A
operand and assign the
result to left operand

Divide AND assignment


/= operator, It divides left C /= A is equivalent to C = C / A
operand with the right
operand and assign the
result to left operand

Modulus AND assignment


operator, 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


<<= C <<= 2 is same as C = C << 2
operator

Right shift AND


>>= C >>= 2 is same as C = C >> 2
assignment operator

Bitwise AND assignment


&= C &= 2 is same as C = C & 2
operator

bitwise exclusive OR and


^= C ^= 2 is same as C = C ^ 2
assignment operator

bitwise inclusive OR and


|= C |= 2 is same as C = C | 2
assignment operator

Example://Write a C# program for assignment operator.


Using system;
namespace assignmentoperator
{
class assignmentexample
{
static void Main(string args[])
{
int a=10;
a=a+2; //a+=
console.writeline(a); //12
a=a-4; //a-=
console.writeline(a); //8
a=a*3;
console.writeline(a); //24
a=a/4;
console.writeline(a); //6
console.readline();
}
}
}
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 type. sizeof(int), returns 4.

typeof() Returns the type of a class. typeof(StreamReader);

Returns the address of an &a; returns actual address of the


&
variable. variable.

*a; creates pointer named 'a' to a


* Pointer to a variable.
variable.

If Condition is true ? Then value X


?: Conditional Expression
: Otherwise value Y

Determines whether an object is If( Ford is Car) // checks if Ford is


Is
of a certain type. an object of the Car class.

Object obj = new


Cast without raising an exception StringReader("Hello");
As
if the cast fails.
StringReader r = obj as
StringReader;

C# expression
“An expression is a sequence of one or more operands and zero or more
operators that can be evaluated to a single value, object, method, or
namespace. “
Example:
int a = 1 + 2;
Control statements in C#
if statement
An if statement consists of a boolean expression followed by one or more
statements.

The following is the syntax −


if(boolean_expression)
{
/* statements here */
}
Example:
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}

}
}

if-else statement
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.

The following is the syntax −


if(boolean_expression)
{
/* statement */
}
else
{
/* statement*/
}
Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}

}
}

if-else-if ladder Statement


The C# if-else-if ladder statement executes one condition from multiple
statements.

Syntax:
if(condition1)
{
//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
}
Example
using System;
namespace ifstatement
{
class ifcondition
{
static void Main(string[] args)
{
int x = 5, y = 20;
if (x > y)
{
if (x >= 10)
{
Console.WriteLine("x value greater than or equal to 10");
}
else
{
Console.WriteLine("x value less than 10");
}
}
else
{
if (y <= 20)
{
Console.WriteLine("y value less than or equal to 20");
}
else
{
Console.WriteLine("y value greater than 20");
}
}
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}

Switch statement
 Switch statement is a multiway decision making statement.
 Switch case allows only integer and character constants in case
expression. We can't use float values.
 It executes case only if input value matches otherwise default case
executes.
 Break keyword can be used to break the control and take out
control from the switch. It is optional and if not used, the control
transfer to the next case.
 Switch case is very useful while developing menu driven
applications.
 Switch cases can't have variable expressions ex. (a+2*b+3).
 No duplicate case expression is allowed.

The general syntax is


switch(expression)
{
case value1:
// statements
case value2:
// statements
. …………………………
case valuen:
// statements
default:
// statements
}

Example
using system;
namespace switchstatement
{
class switchcondition
{
static void Main(String args[])
{
int num = 2;
switch(num)
{
case 1:
printf("One");
break;

case 2:
printf("Two");
break;

case 3:
printf("Three");
break;
default:

printf("value is other than 1, 2, 3");


}
return 0;
}
}
}

Looping structure
C# has four different control structures that allow programmers
use to perform repetitive tasks:
 The while loop.
 The do-while loop.
 The for loop.
 The foreach loop.

 for loop
It executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.

The following is the syntax −


for ( initialization ; condition; increment )
{
statement(s);
}
Example: // write a c#.net for loop.
using System;
namespace TestApplication
{
class Program
{
static void Main(string[] args)
{
for (int j = 0; j < 10; j++)
{
Console.WriteLine(j);
}
}
}
}

Output:

 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.

The following is the syntax −


while(condition)
{
statement(s);
}
Example: // write a c#.net while loop.
using System;
namespace Loop
{
class WhileLoop
{
public static void Main(string[] args)
{
int i=1;
while (i<=5)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
i++;
}
}
}
}

Output:
C# For Loop: Iteration 1
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5

 do…while loop
It is similar to a while statement, except that it tests the condition at the
end of the loop body.
The following is the syntax −
do
{
statement(s);
}
while( condition );
Example: //write a c#.net do-while loop.
using System;
namespace Loop
{
class DoWhileLoop
{
public static void Main(string[] args)
{
int i = 1, n = 5, product;
do
{
product = n * i;
Console.WriteLine("{0} * {1} = {2}", n, i, product);
i++;
}
while (i <= 10);
}
}
}

Output:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

 foreach loop
here is also a foreach loop, which is used exclusively to loop through
elements in an array:
The general sysntax is

foreach (type variableName in arrayName)


{
// code block to be executed
}
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
}
}
}

Output:
Volvo
BMW
Ford
Mazda

Method in C#
A method is a code block that contains a series of statements. A
program causes the statements to be executed by calling the method and
specifying any required method arguments.
In C#, every executed instruction is performed in the context of a
method.

Create a Method
A method is defined with the name of the method, followed by
parentheses (). C# provides some pre-defined methods, which you
already are familiar with, such as Main(), but you can also create your
own methods to perform certain actions:
Example
Create a method inside the Program
class:class Program
{
static void MyMethod()
{
// code to be executed
}
}

Call a Method
To call (execute) a method, write the method's name followed by two
parentheses () and a semicolon;
In the following example, MyMethod() is used to print a text (the
action),when it is called:
Example
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
static void Main(string[] args)
{
MyMethod();
}

You might also like