Unit 2 Notes11
Unit 2 Notes11
What is C#?
C# is pronounced as "C-Sharp". It is an object-oriented programming
language provided by Microsoft that runs on .Net Framework.
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.
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();
}
}
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.
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”
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;
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;
Output :
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.
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);
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
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.
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
Relational Operators
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
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
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assignment Operators
Simple assignment
operator, Assigns values C = A + B assigns value of A + B
=
from right side operands into C
to left side operand
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.
}
}
if-else statement
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
}
}
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.
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:
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.
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.
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
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();
}