You are on page 1of 68

Session 3

Total.net / Programming in C# / Session 3/ 1 of 38

Features of C#
Simple Consistent Modern Object Oriented Type Safe Versionable Compatiable Interoperable and Flexible
Total.net / Programming in C# / Session 3/ 2 of 38

Simple: Treats integer and Boolean types as 2 differently types Consistance: All Types are treated as objects and developers can extend the type system simply and easily Modern: It supports garbage collection. Rich intrinsic model for error handling Security Model
Total.net / Programming in C# / Session 3/ 3 of 38

Object Oriented
Data Abstraction Encapsulation Inheritance Polymorphism

Total.net / Programming in C# / Session 3/ 4 of 38

Type Safety
All dynamically allocated objects and arrays are intialized to zero. Use of unintialized variables produces an error message by the compiler .

Total.net / Programming in C# / Session 3/ 5 of 38

Versionable
Making new versions of software modules work with the existing applications is known as Versioning

Total.net / Programming in C# / Session 3/ 6 of 38

Compatiable and Flexible,Interoperablity


Interoperation with other languages is possible. C# does not support pointers we may declare certain classes and methods as unsafe and then use pointers to manipulate them
Total.net / Programming in C# / Session 3/ 7 of 38

C# Compared with C++


In c# class definition does not use the semicolon at the end. The first character of Main is capitalized. C# does not support #include statement All data types are inherited from objects. Data types are value types or reference types
Total.net / Programming in C# / Session 3/ 8 of 38

C# checks for unintialized variables and gives error messages at compile time.In C++ an unintialized variable goes undetected thus resulting in unpredictable output. Arrays are classes in C# and therefore they have built in functionality for operations such as sorting and searching.
Total.net / Programming in C# / Session 3/ 9 of 38

C++ Features dropped


Macros Multiple Inheritance Templates Pointers Global Variables TypeDef statement Default Arguments
Total.net / Programming in C# / Session 3/ 10 of 38

C# Differ From JAVA


Java uses static final to declare a class constant while C# uses const. C# supports struct type and Java does not. Java does not provide for operator overloading. C# provides delegates and events .Java uses interfaces and inner classes to achieve same result
Total.net / Programming in C# / Session 3/ 11 of 38

Java does not support enumerations,indexers. C# does not allow type definitions in interfaces while java interfaces can have const type data. In Java switch statement can have only integer expression while C# supports either an integer or strings.
Total.net / Programming in C# / Session 3/ 12 of 38

Session Objectives
Explain the need for C# Discuss classes in C# Discuss flow control of a program Explain the fundamental data types in C# Discuss the concept of Boxing and UnBoxing Discuss Structures Appreciate the new features of structures in C# Discuss Enumeration types
Total.net / Programming in C# / Session 3/ 13 of 38

Introduction to C#
Takes Full Advantage of the .net Platform A modern replacement for C++. Enhances developer productivity and increases safety, by enforcing script type checking.

Total.net / Programming in C# / Session 3/ 14 of 38

C# Program Flow
A simple C# program -

Total.net / Programming in C# / Session 3/ 15 of 38

C# Constructs (1)
Variables in C# are declared as follows -

Total.net / Programming in C# / Session 3/ 16 of 38

C# Constructs (2)
If you want to use any keyword as the variable name, you have to prefix the variable name with @.

Total.net / Programming in C# / Session 3/ 17 of 38

C# Constructs (3)

Output -

Total.net / Programming in C# / Session 3/ 18 of 38

Default Values
The default values of the common data types -

Total.net / Programming in C# / Session 3/ 19 of 38

Escape Characters
\.. double quotes. \ single quotes. \nnewline. \t..tab Eg:Path=C:\\myfolder\\myfile.txt. Or Path=@c:\myfolder\myfile.txt.
Total.net / Programming in C# / Session 3/ 20 of 38

Input / Output In C# (1)


Uses methods of the Console class in the System namespace The most widely used methods are -

Total.net / Programming in C# / Session 3/ 21 of 38

Input / Output In C# (2)

The highlighted line acts as a placeholder where the value of the specified variable (result) will be displayed.
Total.net / Programming in C# / Session 3/ 22 of 38

Input / Output In C# (3)

The program will accept a line from the user and echo it back as output.
Total.net / Programming in C# / Session 3/ 23 of 38

The if construct
Used for performing conditional branching. Syntax -

The expression always requires to evaluate to an expression of Boolean type.


Total.net / Programming in C# / Session 3/ 24 of 38

Selection Statement
The above piece of code will display an error message -

Total.net / Programming in C# / Session 3/ 25 of 38

Syntax

The switch Statement (1)

Total.net / Programming in C# / Session 3/ 26 of 38

The switch Statement (2)


Example -

Total.net / Programming in C# / Session 3/ 27 of 38

Perform a certain set of instructions a certain number of times or while a specific condition is true. Types of iteration constructs -

Iteration Constructs

Total.net / Programming in C# / Session 3/ 28 of 38

The while loop


The while loop iterates through the specified statements till the condition specified is true. Syntax -

The break statement - to break out of the loop at anytime. The continue statement - to skip the current iteration and begin with the next iteration.
Total.net / Programming in C# / Session 3/ 29 of 38

The do loop
Syntax -

Total.net / Programming in C# / Session 3/ 30 of 38

The for loop


Syntax -

Total.net / Programming in C# / Session 3/ 31 of 38

The foreach loop is used to iterate through a collection or an array. Syntax -

The foreach loop (1)

Total.net / Programming in C# / Session 3/ 32 of 38

The foreach loop (2)


Example -

Output -

Total.net / Programming in C# / Session 3/ 33 of 38

Foreach Example
This will work String[] str={one,two,three} foreach(string s in str) { System.Console.WriteLine(s= ); } This will not work int [] arr={1,2,3}; foreach(int num in arr) { Num+=1; } Here one requires to use for block with counter.

Total.net / Programming in C# / Session 3/ 34 of 38

Constructors in C#
A constructor in C# has a same name as the class

Total.net / Programming in C# / Session 3/ 35 of 38

Destructors in C#
A destructor in C# also has a same name as the class.

Total.net / Programming in C# / Session 3/ 36 of 38

Passing parameters in methods


Passing by value Passing by reference Passing by out keyword. Passing by value: copy of a variable data is Passed to the calling function. Passing by reference: A reference is passed. use of ref keyword or out keyword.
Total.net / Programming in C# / Session 3/ 37 of 38

ref keyword
private void M1(ref int number) { number=number+2; } Calling function int n=10; M1(ref n) System.Console.WriteLine(n); Output..12
Total.net / Programming in C# / Session 3/ 38 of 38

Output parameter
It is a parameter that is passed from the called method to the method that called it-that is in reverse direction. They are useful when you want a method to return more than a single value. Output parameters are passed by reference and do not require initialization before use. Public void aWord(out string Word) { Word=Vibrant; } Public void showword() { String Word; aWord(out Word); Console.WriteLine(Word); } Total.net / Programming in C# / Session 3/ 39 of 38

Data Types C# Data Types

Value Types

Pointers

Reference Types

Predefined Types

User Defined Types

Predefined Types

User Defined Types

Integers Real Numbers Boolean Characters

Enumerations Structures

Objects Strings

Classes Arrays Delegates Interfaces

Total.net / Programming in C# / Session 3/ 40 of 38

Fundamental Types Of C# (1)


C# divides data types into two fundamental categories - int, char , and structures.

- classes, interfaces, arrays and strings.


Total.net / Programming in C# / Session 3/ 41 of 38

Fundamental Types Of C# (2)


just hold a value in the memory.
Are stored in a stack. Contains the address of the object in the heap. = null means that no object has been referenced.
Total.net / Programming in C# / Session 3/ 42 of 38

Value Types
int X ,Y; X=15; Y=X; X=30; The value of Y? Ans= Y is 15 X and Y are two separate variables and has no effect when change is made.
Total.net / Programming in C# / Session 3/ 43 of 38

Value Types
Example -

Output -

Total.net / Programming in C# / Session 3/ 44 of 38

Reference Type
System.Windows.Forms.Form x,y; X=new System.Windows.Forms.Form(); X.Text=This is Form1; Y=X; X.Text=This is form2; The value of Y? Ans Y is now This is Form2 Here the variable does not contain a Form but just points to the instance of the form.In case of Y=X, Variables X and Y now points to the same instance of the form.Thus returning the same value.
Total.net / Programming in C# / Session 3/ 45 of 38

Reference Types
Example -

Output

Total.net / Programming in C# / Session 3/ 46 of 38

Value types vs. Reference types

Total.net / Programming in C# / Session 3/ 47 of 38

Boxing & Unboxing


Boxing is conversion of a value type into a reference type. int i=42;//value tpe Object o=i;//I is boxed to o Unboxing is the conversion of a reference type into a value type. You have to perform explicit cast on the object to convert it to the appropriate type. Int i=42;//value type Object o=i;//I is boxed to o Int p=(int)o;//unboxed back to int
Total.net / Programming in C# / Session 3/ 48 of 38

Data Types In C#
C# provides us with a Unified Type System.
All data types in C#, are derived from just one class, the object class

Total.net / Programming in C# / Session 3/ 49 of 38

Casting Between the Types


Widening And Narrowing Widening: Eg:
1.Any number converted to a String type. 32bit int to 64 bit int;

Narrowing int a=1000; Short B; B=(short)a;//compile error.


Total.net / Programming in C# / Session 3/ 50 of 38

Solve Type Casting


int Count; string str=10; Count=System.Convert.ToInt32(str) Or int Count; String str=10; Count=Int32.parse(str);

Total.net / Programming in C# / Session 3/ 51 of 38

Object Based Manipulation


Variables are also fully fleged objects. String Str; int newint=1000; Str=newint.ToString();

DateTime Newd=DateTime.Now; Newdt=Newdt.AddDays(60); String str=Newdt.Year.Tostring();


System.DateTime newdt=DateTime.Now; No need to create object of DateTime class.
Total.net / Programming in C# / Session 3/ 52 of 38

Static Members
Members are not associated with any particular object or the class. Only one instance possible

Total.net / Programming in C# / Session 3/ 53 of 38

Arrays(1)
A group of values of similar data type. Belong to the reference type and hence are stored on the heap.

The declaration of arrays in C# follow the syntax given below DataType[number of elements] ArrayName;

int[6] arr1;
Total.net / Programming in C# / Session 3/ 54 of 38

Arrays(2)
Declaring an Array Variable Does Not Create an Array!
You must use new to explicitly create the array instance long[ ] row = new long[4]; 0 0 0 0 Array elements have an implicit default value of zero Variable
int[,] grid = new int[2,3];
grid

0 0 0 0 0 0
Total.net / Programming in C# / Session 3/ 55 of 38

ArrayList
For dynamic array,as c# does not have rediminising.(one can change its size). ArrayList Arr=new ArrayList(); Arr.Add(one); Arr.Add(two); Arr.Add(three); String items=Convert.Tostring(Arr[0]);
Total.net / Programming in C# / Session 3/ 56 of 38

Structures
Custom data Types Can have methods Can have constructors Cannot implement inheritance

Total.net / Programming in C# / Session 3/ 57 of 38

Enumerators (1)
Are a set of named constants.

Total.net / Programming in C# / Session 3/ 58 of 38

Enumerators (2)
Enumerators in C# have numbers associated with the values. By default, the first element of the enum is assigned a value of 0 and is incremented for each subsequent enum element. The default value can be overridden during initialization.

Total.net / Programming in C# / Session 3/ 59 of 38

System.String class
String Str=This is a test string ; Str=Str.Trim()// This is a test string Str=Str.substring(0,4);// This Str=Str.Replace(is,at)// That Str=Str.ToUpperCase()//THIS IS A TEST STRING
Total.net / Programming in C# / Session 3/ 60 of 38

Example on String class


String[] str={One,Two,Three}; for(int i=0;i<=str.GetUpperBound(0);i++) { System.Console.WriteLine(str[i]+ ); }

OutputOne Two Three.


Total.net / Programming in C# / Session 3/ 61 of 38

Why Use Exceptions?


Traditional Procedural Error Handling Is Core program logic Cumbersome
int errorCode; File source = new File("code.cs"); if (errorCode == -1) goto Failed; int length = (int)source.Length; if (errorCode == -2) goto Failed; char[] contents = new char[length]; if (errorCode == -3) goto Failed; // Succeeded ... Failed: ...

Error handling

Total.net / Programming in C# / Session 3/ 62 of 38

Exception Objects
Exception
IOException SystemException OutOfMemoryException OverflowException CoreException Represents fatal run-time errors Represents non-fatal run-time errors

NullReferenceException

Total.net / Programming in C# / Session 3/ 63 of 38

Using try and catch Blocks


Object-Oriented Solution to Error Handling
Put the normal code in a try block Handle the exceptions in a separate catch block
Core program logic

try { File source = new File("code.cs"); int length = (int)source.Length; char[ ] contents = new char[length]; ... } catch (System.Exception caught) { Console.WriteLine(caught); }

Error handling

Total.net / Programming in C# / Session 3/ 64 of 38

Multiple catch Blocks


Each catch Block Catches One Class of Exception A try Block Can Have One General Catch Block
try { File source = new File("code.cs"); int length = (int)source.Length; char[ ] contents = new char[length]; ... } catch (SecurityException caught) { ... } catch (IOException caught) { ... } catch (OutOfMemoryException caught) { ... }
Total.net / Programming in C# / Session 3/ 65 of 38

The throw Statement


Throw an Appropriate Exception Give the Exception a Meaningful Message
throw expression ; if (minute < 1 || minute > 59) { throw new InvalidTimeException(minute + "is not a valid minute"); // !! Not reached !! }

Total.net / Programming in C# / Session 3/ 66 of 38

The finally Clause


All of the Statements in a finally Block Are Always Executed
CriticalSection.Enter(x); try { ... } finally { CriticalSection.Exit(x); }
Any catch blocks are optional

Total.net / Programming in C# / Session 3/ 67 of 38

Compiling & Running


Step 1 Type your code in Notepad

Step 2 Save the file with a .cs extension


Step 3 Switch to DOS prompt and type the following command.
csc <SourceFileName.cs> csc First.cs

To run the C# file, type the name of the file without the extension.
Total.net / Programming in C# / Session 3/ 68 of 38