135
By G.Pavani Introduction to Introduction to C# C# By G.Pavani By G.Pavani Co-operate trainer & Developer Integrated Solutions Inc. [email protected]

Csharp3.5

Embed Size (px)

Citation preview

Page 1: Csharp3.5

By G.Pavani

Introduction to C# Introduction to C# Introduction to C# Introduction to C#

By By G.PavaniG.Pavani

Co-operate trainer & Developer

Integrated Solutions [email protected]

Page 2: Csharp3.5

By G.Pavani

Why C# ?

• Builds on COM+ experience• Native support for

– Namespaces– Versioning– Attribute-driven development

• Power of C with ease of Microsoft Visual Basic®

• Minimal learning curve for everybody• Much cleaner than C++• More structured than Visual Basic• More powerful than Java

Page 3: Csharp3.5

By G.Pavani

C# – The Big IdeasA component oriented language

• The first “component oriented” language in the C/C++ family – In OOP a component is: A reusable program that can be

combined with other components in the same system to form an application.

– Example: a single button in a graphical user interface, a small interest calculator

– They can be deployed on different servers and communicate with each other

• Enables one-stop programming– No header files, IDL, etc.– Can be embedded in web pages

Page 4: Csharp3.5

By G.Pavani

New Features in C#• Reference and Output Parameters.• Rectangular Arrays.• Versioning.• Enumeration.• Component-based programming.• Delegates and Indexers.• Operation Overloading.• ForEach Statements.• Boxing/Unboxing.• Attributes.

Page 5: Csharp3.5

By G.Pavani

Characteristics Of C#

1. Elegant object oriented design: The concurrence with these golden principles of object orientation, encapsulation, inheritance and polymorphism, has made C# programming a great choice for architecting a wide range of components from high-level business objects to system - level software applications.

2.   Safety and Productivity: In C#, the unsafe code must be explicitly declared with the modifier as 'unsafe' to prevent accident features. Moreover, the compiler and execution engine works hand in hand to ensure that the unsafe code is not executed in an unreliable environment.

3.    Name spaces: C# does its job in a hierarchical name space model. Namespaces are C# program elements which help to organize programs. Objects are grouped into name spaces and a particular namespace has to be included in a software program to access the classes and objects within it.

4. Security: In C#, unsafe codes must be explicitly declared unsafe by the modifier to prevent accident features. Moreover the compiler and execution engine work hand in hand and ensure that an unsafe code is not executed in an unreliable environment

Page 6: Csharp3.5

By G.Pavani

5. Garbage collection: The memory management feature leads all managed objects. Garbage collection is a feature of .NET that C# uses during runtime.

6. Data types: This is a regulatory type language set rules to maintain the integrity of data stored in it. Three types of data types include value types, reference types, boxing and unboxing. There are also simple types namely integral type, Boolean type, char type, floating- point type, decimal type, structure type, and enumeration type.

7. Versioning: C# programming supports this versioning. . NET solves the versioning problem and enables the software developer to specify version dependencies between different pieces of software.

8. Indexes: C# has indexes which help to access value in a class with an array like syntax.

9. Exception handling: . NET standardizes the exception handling across languages. C# offers the conditional keyword to control the flaw and make the code more readable.  

Characteristics Of C#

Page 7: Csharp3.5

By G.Pavani

10. Error Elimination: C# programming eliminates costly software programming errors, through garbage collection which are automatically initialized by the environment type safe variables. C# makes it simple for the software developer to write and maintain programs that give solutions for complex business problems.

11.      Flexibility & Power: C# has the flexibility which permits typed, extensible metadata that can be applied to any object. A project architect can define domain-specific attributes and apply them to any language, element, classes, interfaces and so on.

12.      Extensive inter-operability: Almost all enterprise software applications can be managed easily by type-safe environment. This extensive inter-operability makes C# the obvious choice for most of the software developers.

Characteristics Of C#

Page 8: Csharp3.5

By G.Pavani

C# Overview

• Object oriented• Everything belongs to a class

– no global scope

• Complete C# program:

using System;namespace ConsoleTest{

class Class1{

static void Main(string[] args){}

}}

Page 9: Csharp3.5

By G.Pavani

C# Program Structure

• Namespaces– Contain types and other namespaces

• Type declarations– Classes, structs, interfaces, enums,

and delegates

• Members– Constants, fields, methods, properties, indexers, events,

operators, constructors, destructors

• Organization– No header files, code written “in-line”– No declaration order dependence

Page 10: Csharp3.5

By G.Pavani

Classes, Members and Methods

• Everything is encapsulated in a class• Can have:

– member data– member methods

Class clsName { modifier dataType varName; modifier returnType methodName (params) {

statements; return returnVal;

} }

Page 11: Csharp3.5

By G.Pavani

Hello World

using System;

namespace Sample{

public class HelloWorld { public static void Main(string[] args) { Console.WriteLine("Hello World!"); return 0; } }

}

Page 12: Csharp3.5

By G.Pavani

Main Method

public static void Main(string[] args){//Some Code

}

Access Specifier

To call the Main Method without Creating the Object

Return Type

Main Method

Arguments

Page 13: Csharp3.5

By G.Pavani

Hello World Anatomy

• Contained in its own namespace• References other namespaces with

"using"• Declares a publicly accessible

application class• Entry point is "static void Main( ... )"• Writes "Hello World!" to the system

console– Uses static method WriteLine on

System.Console

Page 14: Csharp3.5

By G.Pavani

How does C# work ?

CPUcodeCPUcode

cscJIT.cs.cs

Source CodeSource Code

.exe.dll.exe.dll

Microsoft Intermediate Language (MSIL)

Microsoft Intermediate Language (MSIL)

CLS CompliantLanguages

CLS CompliantLanguages

Page 15: Csharp3.5

By G.Pavani

Simple Types• Integer Types

– byte, sbyte (8bit), short, ushort (16bit)– int, uint (32bit), long, ulong (64bit)

• IEEE Floating Point Types– float (precision of 7 digits)– double (precision of 15–16 digits)

• Exact Numeric Type– decimal (28 significant digits)

• Character Types– char (single character)– string (rich functionality, by-reference type)

• Boolean Type– bool (distinct type, not interchangeable with int)

Page 16: Csharp3.5

By G.Pavani

Data Types

Page 17: Csharp3.5

By G.Pavani

Difference between Value Type and Reference Type

Value Type Reference Type

The variable contains the value directly.

The variable contains a reference to the data.

Allocated on Stack. Allocated on heap using new keyword.

Assigned as copies. Assigned as references.

Default behavior is pass by values.

Passed by references.

== and != compares the values.

== and != compares the references, not the values.

Simple types, structs, enums . Classes.

Page 18: Csharp3.5

By G.Pavani

Data

• All data types derived from System.Object

• Declarations:datatype varname;datatype varname = initvalue;

• C# does not automatically initialize local variables (but will warn you)!

Page 19: Csharp3.5

By G.Pavani

Value Data Types

• Directly contain their data:– int (numbers)– long (really big numbers)– bool (true or false)– char (unicode characters)– float (7-digit floating point numbers)– string(multiple characters together)

Page 20: Csharp3.5

By G.Pavani

strings

• Immutable sequence of Unicode characters (char)

• Creation:– string s = “Bob”;– string s = new String(“Bob”);

• Backslash is an escape:– Newline: “\n”– Tab: “\t”

Page 21: Csharp3.5

By G.Pavani

string/int conversions

• string to numbers:

– int i = int.Parse(“12345”);– float f = float.Parse(“123.45”);

• Numbers to strings:

– string msg = “Your number is ” + 123;– string msg = “It costs ” + string.Format(“{0:C}”, 1.23);

Page 22: Csharp3.5

By G.Pavani

String Example

using System; namespace ConsoleTest {

class Class1{

static void Main(string[ ] args){

int myInt;string myStr = "2";bool myCondition = true;

Console.WriteLine("Before: myStr = " + myStr);myInt = int.Parse(myStr);myInt++;myStr = String.Format("{0}", myInt);Console.WriteLine("After: myStr = " + myStr);

while(myCondition) ;}

} }

Page 23: Csharp3.5

By G.Pavani

OperatorsThe operators are symbols and characters to perform an operation.When using operators, there must be a return value of the performed operation.The operators are defined on the basis of type.

using System; namespace Operators { class Class1 { static void Main(string[] args) { int x = 10; int y = 5; int result;

result = x + y; Console.WriteLine("x + y = {0}", result);

result = x - y; Console.WriteLine("x - y = {0}", result);

result = x * y; Console.WriteLine("x * y = {0}", result);

result = x / y; Console.WriteLine("x / y = {0}", result);

Console.ReadLine(); } } }

EXAMPLE

X+y=15X-y=5X*y=50X/y=2

Output:Output:

Page 24: Csharp3.5

By G.Pavani

Arithematic OperatorsC# supports the basic arithmetic operators: 1.Addition operator (+)2.Multiplication operator (*)3.Subtraction operator (-)

using System; namespace Operators { class Class1 { static void Main(string[] args) { int x = 10; int y = 5; int result;

result = x + y; Console.WriteLine("x + y = {0}", result);

result = x - y; Console.WriteLine("x - y = {0}", result);

result = x * y; Console.WriteLine("x * y = {0}", result);

result = x / y; Console.WriteLine("x / y = {0}", result);

Console.ReadLine(); } } }

EXAMPLE

X+y=15X-y=5X*y=50X/y=2

Output:Output:

4.Division operator(/)5.Module operator (%).6.Increment and decrement operators (++ and --)

Page 25: Csharp3.5

By G.Pavani

Unary OperatorThere are two more arithmetic operators, but they are unary operators not binary operators.Binary Operators work on two arguments. The unary operators work on one argument only; C# defines two unary arithmetic operators, the minus operator (-) and the plus operator (+)

using System; namespace Operators { class Class1 { static void Main(string[] args) { int x = -10; int y = +10; int z = +-10; int original = 3; int result; Console.WriteLine("x = {0}, y = {1}, z = {2}",x,y,z);

z = -10; result = z * original; Console.WriteLine("result = {0}", result); result = z * +original; Console.WriteLine("result = {0}", result); Console.ReadLine(); } } }

EXAMPLE

X=-10,Y=10,z=-10Result=-30Result=-30

Output:Output:

Page 26: Csharp3.5

By G.Pavani

Logical OperatorC# has eight logical operators, which form logical expressions. Logical expressions are used with control structure statements.Logical expressions work on Boolean Arguments and produce Boolean value . C# logical operators include: 1.NOT operator (!)2.XOR (^) or the Exclusive OR Operator, 3.Short Circuit And Operator (&&)4.AND Operator (&), 5.Short Circuit OR Operator (||) and the OR Operator (|).

using System; namespace Operators { class Class1 { static void Main(string[] args) { int x = 10;Int y = 5;bool result;

bool another;

// using the NOT Operator Console.WriteLine("Using the ! Operator"); result = true; Console.WriteLine("result before using ! equal to = {0}", result); result = !result; Console.WriteLine("result after using ! equal to = {0}", result); }}}

EXAMPLE

Using the ! Operator10,Y=10,z=-10result before using ! equal to=Trueresult before using ! equal to=false

Output:Output:

Page 27: Csharp3.5

By G.Pavani

Assignment

OperatorsC# has many assignment operators other than the simple = operator. 1.Addition assignment operator (+=)2.Subtraction assignment operator (-=)3.Multiplication assignment operator (*=)4.Division assignment operator (/=)5.Module assignment operator (%=)6.Bitwise assignment operators

using System; namespace Operators { class Class1 { static void Main(string[] args) { int x = 5; int y = 5;

x = x + y; Console.WriteLine("y assigned to x and x = {0}",x + y); x += y; Console.WriteLine("Using the += operator x = {0}", x);

Console.WriteLine("**********");

x = x - y; Console.WriteLine("x = x - y and x = {0}",x - y); x -= y; Console.WriteLine("Using the -= operator x = {0}", x);

Console.WriteLine("**********");

EXAMPLE

x assigned to x and x =15Using the +=operator x=15**********X=x-5 and x=5Using the -=operator x=5**********

Output:Output:

Page 28: Csharp3.5

By G.Pavani

There's only one ternary operator in C#, the (?:) ternary operator. It has three arguments. This operator is very useful in writing elegant C# code because its first argument takes a Boolean expression.If it's evaluated to true, the second argument executes.If it's evaluated to false, the third argument executes.

using System; namespace Operators { class Class1 { static void Main(string[] args) { int x = 5; if(x == 5) { Console.WriteLine("x equal to 5");

}

else { Console.WriteLine("x not equal to 5"); } }}}EXAMPLE

X equal to 5

Output:Output:

Ternary Operator

Page 29: Csharp3.5

By G.Pavani

Statements and Comments

• Case sensitive (myVar != MyVar)• Statement delimiter is semicolon ;• Block delimiter is curly brackets

{ }• Single line comment is //• Block comment is /*

*/– Save block comments for debugging!

Page 30: Csharp3.5

By G.Pavani

An expression statement evaluates a given expression. The value computed by the expression, if any, is discarded.

The first selection statement is programmer's favorite "if" statement. It has three forms:1. Single selection 2. if-then-else selection 3. multi-case selection

Branching statements

Page 31: Csharp3.5

By G.Pavani

using System;class IfTest {public static void Main(){string s;int i;Console.WriteLine("Enter a Number: ");s = Console.ReadLine();i = Int32.Parse(s);

//single selectionif(i > 0)Console.WriteLine("The number {0} is positive",i);

//if-then-else selectionif(i > 0)Console.WriteLine("The number {0} is positive",i);elseConsole.WriteLine("The number {0} is not positive",i);

//multi-case selectionif(i == 0)Console.WriteLine("The number is zero");else if(i > 0)Console.WriteLine("The number {0} is positive",i);elseConsole.WriteLine("The number {0} is negative",i);}}

Enter a number-7The number –7 is not positiveThe number –7 is negative

Enter a number5The number 5 is positiveThe number 5 is positiveThe number 5 is positive

If statement Example

Output:Output:

Branching statements

Page 32: Csharp3.5

By G.Pavani

SWITCH STATEMENTS The switch statement is similar to multiple else if statements, but it accepts only expressions that will evaluate to constant values. The if/else structure is appropriate for small groups of Boolean expressions.

This is the syntax of a switch statement:switch(expression) {   case constant-value:     statement 1;     statement 2;     jump statement   case constant-value:     statement 1;     statement 2;     jump statement   default:     statement 1;     statement 2;     jump statement }

Branching statements

Page 33: Csharp3.5

By G.Pavani

using System;class SwitchSelect{    public static void Main()    {        string myInput;        int myInt;       begin:        Console.Write("Please enter a number between 1 and 3: ");        myInput = Console.ReadLine();        myInt = Int32.Parse(myInput);        // switch with integer type        switch (myInt)        {            case 1:                Console.WriteLine("Your number is {0}.", myInt);                break;            case 2:                Console.WriteLine("Your number is {0}.", myInt);                break;            case 3:                Console.WriteLine("Your number is {0}.", myInt);                break;            default:                Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);                break;        }       decide:        Console.Write("Type \"continue\" to go on or \"quit\" to stop: ");        myInput = Console.ReadLine();       

        // switch with string type        switch (myInput)        {            case "continue":                goto begin;            case "quit":                Console.WriteLine("Bye.");                break;            default:                Console.WriteLine("Your input {0} is incorrect.", myInput);                goto decide;        }    }}

Please enter a number between 1 and 3:1Your number is 1Type “ continue” to go on or “quit” to stop:continuePlease enter a number between 1 and 3:2Your number is 2Type “ continue” to go on or “quit” to stop:stopYour input stop is incorrectType “ continue” to go on or “quit” to stop:quitBye

SWITCH Example

Output:Output:

Branching statements

Page 34: Csharp3.5

By G.Pavani

A while loop will check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true.

Its syntax is as follows:

while (<boolean expression>) { <statements> }.

using System;

class WhileLoop{    public static void Main()    {        int myInt = 0;

        while (myInt < 10)        {            Console.Write("{0} ", myInt);            myInt++;        }      }}

0 1 2 3 4 5 6 7 8 9

WHILE statementsExample

Looping statement

Output:Output:

Page 35: Csharp3.5

By G.Pavani

A 'do-while' loop is just like a 'while' loop except that the condition is evaluated after the block of code specified in the 'do' clause has been run.

If the condition is initially false, the block runs once.

Syntax

do {statement[s] }while (expression)

using System;

class WhileLoop{ public static void Main()  { int a = 4; do {  System.Console.WriteLine(a);  a++;} while (a < 8);       }

4567

DO WHILE statements Example

Looping statement

Output:Output:

Page 36: Csharp3.5

By G.Pavani

A for loop works like a while loop, except that the syntax of the for loop includes initialization and condition modification.

For loops are good for when you know exactly how many times you want to perform the statements within the loop.

The contents within the for loop parenthesis holds three sections separated by semicolons

SYNTAXfor(<initializerlist>;<booleanexpression>;<iterator list>) { <statements> }. The initializer list is a comma separated list of expressions.

using System;class ForLoop{public static void Main(){ for (int i=0; i < 20; i++) { if (i == 10) break; if (i % 2 == 0) continue;

Console.Write("{0} ", i); }//For Loop End here}}

13579

FOR statements Example

Looping statement

Output:Output:

Page 37: Csharp3.5

By G.Pavani

A foreach loop is used to iterate through the items in a list.

It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace.

syntax

foreach (<type> <item name> in <list>) { <statements> }.

using System;

class ForEachLoop{    public static void Main()    {        string[] names = {"Cheryl", "Joe", "Matt", "Robert"};

    foreach (string person in names)     {     Console.WriteLine("{0} ", person);     }    }}

CheryJoeMattRobert

FOREACH statements Example

Looping statement

Output:Output:

Page 38: Csharp3.5

By G.Pavani

• Zero based, type bound• Built on .NET System.Array class• Declared with type and shape, but no bounds

– int [ ] SingleDim; – int [ , ] TwoDim; – int [ ][ ] Jagged;

• Created using new with bounds or initializers– SingleDim = new int[20];– TwoDim = new int[,]{{1,2,3},{4,5,6}};– Jagged = new int[1][ ]; Jagged[0] = new int[ ]{1,2,3};

Arrays

Page 39: Csharp3.5

By G.Pavani

int [] intArray;

int [] intArray;intArray = new int[5];

int [] intArray;intArray = new int[100];

It declares an array, which can store 5 items starting from index 0 to 4.

It declares an array that can store 100 items starting from index 0 to 99.

It declares a dynamic array of integers

Arrays

Page 40: Csharp3.5

By G.Pavani

•In C#, an array index starts at zero. That means first item of an array will be stored at 0th position.

•The position of the last item on an array will total number of items - 1.

•In C#, arrays can be declared as fixed length or dynamic.

•Fixed length array can stores a predefined number of items, while size of dynamic arrays increases as you add new items to the array.

•You can declare an array of fixed length or dynamic.

•You can even change a dynamic array to static after it is defined.

Arrays

Page 41: Csharp3.5

By G.Pavani

int [] intArray;intArray = new int[3] {0, 1, 2};

string[] strArray = new string[5] {"Ronnie", "Jack", "Lori", "Max", "Tricky"};

string[] strArray = {"Ronnie", "Jack", "Lori", "Max", "Tricky"};

string[] strArray = new string[] {"Ronnie", "Jack", "Lori", "Max", "Tricky"};

The code declares and initializes an array of three

items of integer type.

The code declares and initializes an array of 5 string

items.

It should direct assign these values without using the new

operator.

It can initialize a dynamic length array as following

Arrays

Page 42: Csharp3.5

By G.Pavani

using System;namespace sampless{

public class ArrayClass {

static void Print Array(string[] w) {

for (int i = 0 ; i < w.Length ; i++) Console.Write(w[i] + "{0}", i <

w.Length - 1 ? " " : "");Console.Write Line();

}

public static void Main() {// Declare and initialize an array:string[] Weekdays = new string []{"Sun","Sat","Mon","Tue","Wed","Thu","Fri"};// Pass the array as a parameter:

Print Array(Weekdays);}}}

Sun Sat Mon Tue Wed Thu Fri

SingleDiamensional Array Example

Arrays

Output:Output:

Page 43: Csharp3.5

By G.Pavani

MULTI DIMENSION ARRAYS

A multidimensional array is an array with more than one dimension. A multi dimension array is declared as following:

string[,] strArray;After declaring an array, you can specify the size of array dimensions if you want a fixed size array or dynamic arrays.

int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };

string[,] names = new string[2, 2] { {"Rosy","Amy"}, {"Peter","Albert"} };

For example, the following code two examples create two multi dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array can store 4 items respectively.

Arrays

Page 44: Csharp3.5

By G.Pavani

public class ArrayClass1 {static void PrintArray(int[,] w) {// Display the array elements:for (int i=0; i < 4; i++) for (int j=0; j < 2; j++)Console.Write Line("Element({0},{1})={2}", i, j, w[i,j]);}

public static void Main(){// Pass the array as a parameter:PrintArray(new int[,] {{1,2}, {3,4}, {5,6}, {7,8}});}}

Element(0,0)=1 Element(0,1)=2 Element(1,0)=3 Element(1,1)=4 Element(2,0)=5 Element(2,1)=6 Element(3,0)=7 Element(3,1)=8

MultiDiamensionalArray Example

Arrays

Output:Output:

Page 45: Csharp3.5

By G.Pavani

public class ArrayTest {public static void Main() {// Declare the array of two elements:int[ ][ ] myArray = new int[2] [ ];// Initialize the elements:

myArray[0] = new int[5] {1,3,5,7,9};myArray[1] = new int[4] {2,4,6,8};

// Display the array elements:for (int i=0; i < myArray.Length; i++) {Console.Write("Element({0}): ", i);for (int j = 0 ; j < myArray[i].Length ; j++)Console.Write("{0}{1}", myArray[i][j],j == (myArray[i].Length-1) ? "" : " ");Console.WriteLine();}}}

Element(0): 1 3 5 7 9 Element(1): 2 4 6 8

JAGGED ARRAY Example

Arrays

Output:Output:

Page 46: Csharp3.5

By G.Pavani

UNDERSTANDING THE ARRAY CLASSThe Array class, defined in the System namespace, is the base class for arrays in C#. •Array class is an abstract base class but it provides CreateInstance method to construct an array. •The Array class provides methods for creating, manipulating, searching, and sorting arrays. ARRAY CLASS PROPERTIES. IsFixedSize : Return a value indicating if an array has a fixed size or not.IsReadOnly : Returns a value indicating if an array is read- only or not.Length : Returns the total number of items in all the dimensions of an array.Rank : Returns the number of dimensions of an array.BinarySearch : This method searches a one-dimensional sorted Array for a value, using a

binary search algorithm.Clear : This method removes all items of an array and sets a range of items in the

array to 0.Clone : This method creates a shallow copy of the Array.Copy : This method copies a section of one Array to another Array and performs type casting and boxing as required.CopyTo : This method copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination.

Arrays

Page 47: Csharp3.5

By G.Pavani

CreateInstance : This method initializes a new instance of the Array class.GetEnumerator : This method returns an IEnumerator for the Array.GetLength : This method returns the number of items in an Array.GetLowerBound : This method returns the lower bound of an Array.GetUpperBound : This method returns the upper bound of an Array.GetValue : This method returns the value of the specified item in an Array.IndexOf : This method returns the index of the first occurrence of a value in a one

dimensional Array or in a portion of the Array.Initialize : This method initializes every item of the value-type Array by calling the default

constructor of the value type.LastIndexOf : This method returns the index of the last occurrence of a value in a one-dimensional

Array or in a portion of the Array.Reverse : This method reverses the order of the items in a one-dimensional Array or in a

portion of the Array.SetValue : This method sets the specified items in the current Array to the specified value.Sort : This method sorts the items in one-dimensional Array objects.

Arrays

Page 48: Csharp3.5

By G.Pavani

Constructor

• A constructor is a special type of method that is invoked when you create a new instance of a class.

• Constructor has the same name as that of the class.• Constructor is used to initialize member variables.• If there are no constructors defined for a class, the

compiler creates a default constructor.

Types of Constructors:• Instance Constructor• Static Constructor

Page 49: Csharp3.5

By G.Pavani

Instance Constructor

An Instance Constructor is called whenever an instance of a class is created

using System;

namespace CSharp{ class Program { static int num1, num2, total; //Constructor Program() { num1 = 10; num2 = 20; } public void AddNum() { total = num1 + num2; } public void DisplayNum() { Console.WriteLine("The total is {0}",total); }

static void Main(string[] args) { Program Obj = new Program(); Obj.AddNum(); Obj.DisplayNum(); } }}

The total is 30

Output:Output:

Page 50: Csharp3.5

By G.Pavani

Static Constructors• Static Constructors are used to initialize the static variables of a class.• They have implicit private access.• The constructor will be invoked only one during the execution of a

program.

class Program { static int num1; int num2; //static Constructor static Program() { num1 = 10; //Ok.Since Num1 is a staic variable. num1 = 20; //Error.Since Num2 is a non-static variable. } }

Page 51: Csharp3.5

By G.Pavani

Constructors with Parameters

using System;

namespace CSharp{ class Program { static int num1, num2, total; //Constructor Program(int No1, int No2) { num1 = No1; num2 = No2; } public void AddNum() { total = num1 + num2; } public void DisplayNum() { Console.WriteLine("The total is {0}",total); }

static void Main(string[] args) { int var1,var2; Console.WriteLine("Enter value 1:"); var1=Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter value 2:"); var2=Convert.ToInt32(Console.ReadLine()); Program Obj = new Program(var1,var2); Obj.AddNum(); Obj.DisplayNum(); Console.ReadLine(); } }} Output:Output:

Enter value 1:10Enter value 2:20The total is 30

Page 52: Csharp3.5

By G.Pavani

Destructors

• Destructors are special methods that are used to release the instance of a class from memory.

• A class can have only one destructor.• The programmer has no control on when to

call the destructor.• Destructor has the same name as its class but

is prefixed with a ~(tilde) symbol.• Even if you don’t call the destructor, garbage

collector releases memory.

Page 53: Csharp3.5

By G.Pavani

class Program { //Constructor Program() { Console.WriteLine("Constructor Invoked"); } //Destructor ~ Program() { Console.WriteLine("Destructor Invoked"); } static void Main(string[] args) { Console.WriteLine("Main Begins"); Program Ojb = new Program(); { Console.WriteLine("Inner Block Begins"); Program Ojb2 = new Program(); Console.WriteLine("Inner Block Ends"); } Console.WriteLine("Main Ends"); } }

Main Begins Inner Block Begins Constructor Invoked Inner Block Ends Main Ends Destructor Invoked

Output:Output:

Page 54: Csharp3.5

By G.Pavani

Polymorphism

• Greek words “poly” and “morphos” mean “many” and “forms” respectively.

• Often expressed as “One Interface, Multiple Functions”.• Polymorphism is the ability that helps in executing

different operations to the same message.

Two types of Polymorphism:

• Static Polymorphism• Dynamic Polymorphism

Page 55: Csharp3.5

By G.Pavani

Static Polymorphism

The mechanism of linking a function with an object during compile time is called early binding or static binding.

Types of Static Binding:• Function Overloading: This approach allows using the same name for two or more function, each redefinition of a function must use different types of parameters, sequence of parameters, or a number of parameters.

• Operator Overloading: This approach allows user-defined types such as structures and classes to use overloading operators for easy manipulation of their objects.

Page 56: Csharp3.5

By G.Pavani

Function overloadingclass Program { public int Max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } public float Max(float num1, float num2) { if (num1 > num2) return num1; else return num2; } static void Main(string[] args) { Program obj = new Program(); Console.WriteLine(“Max Value is : {0}”obj.Max(19,20)); } }

Output:Output:

Max Value is : 20

Page 57: Csharp3.5

By G.Pavani

Constructor Overloadingclass Program { float max; Program(int num1, int num2) { if (num1 > num2) max= num1; else max= num2; } Program(float num1, float num2) { if (num1 > num2) max = num1; else max = num2; } static void Main(string[] args) { Program obj = new Program(10,20); Console.WriteLine("Max is :"+obj.max); } }

Output:Output:

Max Value is : 20

Page 58: Csharp3.5

By G.Pavani

Operator Overloadingclass Program { public int num1, num2; public Program(int num1, int num2) { this.num1 = num1; this.num2 = num2; } public static Program operator - (Program p1) { p1.num1 = -p1.num1; p1.num2 = -p1.num2; return p1; } public void Print() { Console.WriteLine("Number 1= " + num1); Console.WriteLine("Number 2= " + num2); } static void Main(string[] args) { Program Obj = new Program(15,25); //using overloading operator Obj = -Obj; Obj.Print(); } }

Page 59: Csharp3.5

By G.Pavani

The Class can acquires the properties and Methods of another class is called Inheritance.

Example :

Shape - Base Class or Parent Class or Super ClassSquare,Triangle, Circle - Derived Class or Sub class or Child Class

Derived class uses the Properties of Base Class (Eg. Square uses the Properties and Methods of Shape Class)

Class Square

Property - Side

Methods - CalculateArea() - Square()

Class Rectangle

Property - Height - Width

Methods - CalculateArea() - Triangle()

Class Circle

Property - Radius

Methods - CalculateArea() - Circle()

Class Shape

Property - Area - Color

Methods - Display()

Classes can be defined as deriving from a base class. A derived class inherits all of the ancestors protected and public methods and data members.

Inheritance

Page 60: Csharp3.5

By G.Pavani

public class Shape // BASE CLASS{

public double area;public Shape(){area=0.0; }public void display(string ShapeName,double a){

Console.WriteLine("The area of “ +ShapeName +" is "+ a);}

}

Inheritance

Page 61: Csharp3.5

By G.Pavani

public class Square:Shape//DERIVED CLASS

{int Side;public Square(int a){

Side=a;}public void CalculatePerimeter(){area=4 * Side * Side; }

}

public class Circle:Shape //DERIVED CLASS

{int r;public Circle(int radius){

r=radius;}public void CalculateArea(){

area=3.14 * r * r; }

}

Shape (Base Class)

Base Class Member

Inheritance

Page 62: Csharp3.5

By G.Pavani

class MainClass{

[STAThread]static void Main( ){Circle objCircle=new Circle(5);objCircle.CalculateArea(); //Derived Class MethodobjCircle.display("Circle",objCircle.area); // Base Class Method

Square objSquare=new Square(5);objSquare.CalculatePerimeter(); //Derived Class Method

objSquare.display("Square",objSquare.area); // Base Class Method

}}

Circle Class inherits Shape’s “Display()”

Method

Inheritance

Page 63: Csharp3.5

By G.Pavani

Abstract Classes

• Abstract classes are used to provide partial class implementation of an interface. One can complete implementation by using the derived classes.

• Abstract classes contain abstract methods, which can be implemented by the derived class.

• Polymorphism can be implemented by using abstract classes and virtual functions.

• Abstract classes cannot create an instance of an abstract class.• One cannot declare an abstract method outside an abstract

class.• An abstract class cannot be declared sealed.• Abstract methods have to override by the derived class..

Page 64: Csharp3.5

By G.Pavani

64

An abstract class with a non-abstract method.

using System;abstract class MyAbs{public void NonAbMethod(){Console.WriteLine("Non-Abstract Method");}}class MyClass : MyAbs{}class MyClient{public static void Main(){//MyAbs mb = new MyAbs();//not possible to create an instanceMyClass mc = new MyClass();

mc.NonAbMethod(); // Displays 'Non-Abstract Method'}}

Example

OutputNon-Abstract Method

The keyword abstract can be used with both classes and methods in C# to declare them as abstract.

The classes, which we can't initialize, are known as abstract classes. They provide only partial implementations. But another class can inherit from an abstract class and can create their instances.

For example, an abstract class with a non-abstract method.

Abstract class

Page 65: Csharp3.5

By G.Pavani

using System;abstract class MyAbs{public abstract void AbMethod1();public abstract void AbMethod2();}//not necessary to implement all abstract methods//partial implementation is possibleabstract class MyClass1 : MyAbs{public override void AbMethod1(){Console.WriteLine("Abstarct method #1");} }class MyClass : MyClass1{public override void AbMethod2(){Console.WriteLine("Abstarct method #2");}}class MyClient{public static void Main(){MyClass mc = new MyClass();mc.AbMethod1();mc.AbMethod2();}}

Example

By declaring the derived class also abstract, we can avoid the implementation of all or certain abstract methods.

This is what is known as partial implementation of an abstract class.

OutputAbstract method #1Abstract method #2

Partial implementation of an abstract class.

Abstract class

Page 66: Csharp3.5

By G.Pavani

using System;abstract class MyAbs{public void NonAbMethod(){Console.WriteLine("Non-Abstract Method");}public abstract void AbMethod(); // An abstract method}class MyClass : MyAbs//must implement base class abstract methods{public override void AbMethod(){Console.WriteLine("Abstarct method");} }class MyClient{public static void Main(){MyClass mc = new MyClass();mc.NonAbMethod();mc.AbMethod();}} 

Example

OutputNon-Abstract MethodAbstract method

An abstract class can contain abstract and non-abstract methods.

When a class inherits from an abstract, the derived class must implement all the abstract methods declared in the base class.

An abstract method is a method without any method body.

They are implicitly virtual in C#.

A class inherits from abstract class

Abstract class

Page 67: Csharp3.5

By G.Pavani

using System;class MyClass1 // Non-Abstract class{public void Method1(){Console.WriteLine("Method of a non-abstract class");}}abstract class MyAbs : MyClass1 // Inherits from an non-abstract class{public abstract void AbMethod1(); }class MyClass : MyAbs//must implement base class abstract methods{public override void AbMethod1(){Console.WriteLine("Abstarct method #1 of MyClass");}}class MyClient{public static void Main(){MyClass mc = new MyClass();mc.Method1();mc.AbMethod1();}}  

Example

In C#, an abstract class can inherit from another non-abstract class.

In addition to the methods it inherited from the base class, it is possible to add new abstract and non-abstract methods.

OutputMethod of a non-abstract class Abstarct method #1 of MyClass

Abstract class can inherit from another non-abstract class.

Abstract class

Page 68: Csharp3.5

By G.Pavani

using System;abstract class MyAbs{public abstract void AbMethod1();public abstract void AbMethod2();}class MyClass1 : MyAbs{public override void AbMethod1(){Console.WriteLine("Abstarct method #1 of MyClass1");}public override void AbMethod2(){Console.WriteLine("Abstarct method #2 of MyClass1");} }class MyClient{public static void Main(){MyAbs ma1 = new MyClass1();// Polymorphismma1.AbMethod1();ma1.AbMethod2();}}  

Example

An abstract class can also implement from an interface.

In this case we must provide method body for all methods it implemented from the interface

OutputAbstarct method #1 of MyClass1 Abstarct method #2 of MyClass1

Polymorphism

Abstract class

Page 69: Csharp3.5

By G.Pavani

Virtual Functions

• These functions are defined in a class which we want to allow to be implemented by the inherited classes.

• The virtual function could be implemented by the inherited classes in their own way and the call to the method is decided at runtime.

Page 70: Csharp3.5

By G.Pavani

public class Dimensions { public const double PI = Math.PI; protected double x, y; public Dimensions() { } public Dimensions(double x, double y) { this.x = x; this.y = y; } public virtual double Area() { return x * y; } } public class Circle : Dimensions { public Circle(double r) : base(r, 0) { } public override double Area() { return PI * x * x; } }

class Sphere : Dimensions { public Sphere(double r) : base(r, 0) { } public override double Area() { return 4 * PI * x * x; } } class TestClass { static void Main() { double r = 3.0, h = 5.0; Dimensions c = new Circle(r); Dimensions s = new Sphere(r); Console.WriteLine("Area of Circle = {0:F2}", c.Area()); Console.WriteLine("Area of Sphere = {0:F2}", s.Area()); } }

Page 71: Csharp3.5

By G.Pavani

Sealed Classes

• Keyword “sealed” is used to restrict the users from inheriting the class by sealing the class.

• No class can be derived from a sealed class.

• A method can never be declared as sealed.

• An overriden method can also be declared sealed.

Page 72: Csharp3.5

By G.Pavani

using System; sealed class MyClass { public int x; public int y; } class MainClass { public static void Main() { MyClass mC = new MyClass(); mC.x = 110; mC.y = 150; Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); } }

In the preceding example, if you attempt to inherit from the sealed class by using a statement like this:

class MyDerivedC: MyClass {} // Error

You will get the error message:

'MyDerivedC' cannot inherit from sealed class 'MyBaseC'.

In C# a method can't be declared as sealed. However when we override a method in a derived class,

Sealed class

Page 73: Csharp3.5

By G.Pavani

using System; class MyClass1 { public int x; public int y; public virtual void Method() { Console.WriteLine("virtual method"); } } class MyClass : MyClass1 { public override sealed void Method() { Console.WriteLine("sealed method"); } } class MainClass { public static void Main() { MyClass1 mC = new MyClass(); mC.x = 110; mC.y = 150; Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); mC.Method(); } }

• In C# a method can't be declared as sealed.

• However when we override a method in a derived class, we can declare the overrided method as sealed . • By declaring it as sealed, we can avoid further overriding of this method.

OUTPUTX=110;Y=150Sealed method

EXAMPLE

METHOD OVERRIDING IN SEALED

Sealed class

Page 74: Csharp3.5

By G.Pavani

Interfaces

• An interface defines the syntactical contract that all the derived classes should follow.

• An Interface also define properties, methods, events which are known as the members of the interface.

• Interface contains only the declaration of members.

• An Interface can inherit members from an existing interface.

• Interfaces support multiple inheritance.

Page 75: Csharp3.5

By G.Pavani

75

interface IMyInterface{

    void MethodToImplement();}

Defining Interface:An interface can contain one or more methods,properties,indexers and events but none of them are implemented in interface itself.

Syntax:

Interface interface name{

Member declarations;}

Ex:

Here,interface is the keyword and interface name is a valid C# identifier.

Extending An InterfaceHere an interface can be sub interfaced from other interface.The new sub interface will inherit all the members of the super interface in the manner similar to subclasses.

Syntax:

Interface name2:name1{

Members of name2}

Ex:

Interface Addition{

int add(int x,int y)}

Interface compute:Addition{

int sub(int x,int y)}

INTERFACES

Page 76: Csharp3.5

By G.Pavani

Interface Inheritance: using System;

interface IParentInterface{    void ParentInterfaceMethod();}

interface IMyInterface : IParentInterface{    void MethodToImplement();}

class InterfaceImplementer : IMyInterface{    static void Main()    {        InterfaceImplementer iImp = new InterfaceImplementer();        iImp.MethodToImplement();        iImp.ParentInterfaceMethod();    }

    public void MethodToImplement()    {        Console.WriteLine("MethodToImplement() called.");    }

    public void ParentInterfaceMethod()    {        Console.WriteLine("ParentInterfaceMethod() called.");    }}

Output:MethodToImplement() called

ParentInterfaceMethod() called

INTERFACES

Page 77: Csharp3.5

By G.Pavani

Feature Interface Abstract Class

Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public

An abstract class can contain access modifiers for the subs, functions, properties

Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behavior or status then abstract class is better to use.

Speed Requires more time to find the actual method in the corresponding classes.

Fast

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

Differences

Page 78: Csharp3.5

By G.Pavani

File Input And Output

• The file is a collection of data stored on a disk with a specific name and very often with a directory path.

• When we open the file for reading data or writing data, it becomes a stream.

• Stream is a sequence of bytes travelling from soure to a destination over a communication path.

• The operations use the namespace “System.IO”

Two basic streams are:

• Input Stream: used for a read operation• Output Stream: used for performing a write operation.

Page 79: Csharp3.5

By G.Pavani

Class Name Description

FileStream Used to read from and write to any location within a file.

BinaryReader Used to read primitive data types from a binary stream.

BinaryWriter Used to write primitive data types in binary format.

StreamReader Used to read characters from a byte stream.

StreamWriter Used to write characters to a stream.

StringReader Used to read from a string buffer.

StringWriter Used to write into a string buffer.

DirectoryInfo Used to perform operations on directories.

FileInfo Used to perform operations on files.

File Input And Output

Page 80: Csharp3.5

By G.Pavani

FileStream Class

• We can use the FileStream class in the System.IO namespace to read from, to write and to close files.

• This class inherits from the abstract class “Stream”.

FileStream <object_name> = new FileStream(<FileName>,<FileMode enumerator>, <fileAccess enumerator>,<FileShare enumerator>)

Page 81: Csharp3.5

By G.Pavani

FileMode Enumerator

FileMode Functionality

Append Opens the file if it exists and places the cursor at the end of the file or creates new line

Create Creates a new file.

CreateNew Specifies to an operating system that is should create a new file.

Open Opens an existing file.

OpenOrCreate Specifies to the operating system that it should open a file if it exists, else create new file.

Truncate Opens an existing file and truncate it to zero bytes.

Defines various methods for opening files.

Page 82: Csharp3.5

By G.Pavani

File Access Enumerator

This enumerator indicates wheather you want to read data from the file, write to the file, or perform both the operations.

The member of the FileAccess enumerator are:• Read• ReadWrite• Write

Page 83: Csharp3.5

By G.Pavani

FileShare Enumerator

FileShare Functionality

Inheritable Allows a file handle to pass inheritance to the child processes.

None Declines sharing of a current file.

Read Allows opening of a file for reading purpose.

ReadWrite Allows opening a file for the purpose of reading and writing.

Write Allows opening of a file for writing purpose.

Page 84: Csharp3.5

By G.Pavani

StreamReader Class

FileStream fs = new FileStream(“C://Myfile.txt”,FileMode.Open,FileAccess.Read);StreamReader sr = new StreamReader(fs);sr.BaseStream.Seek(0,SeekOrigin.Begin);string str = sr.ReadLine();

Methods

Description

Close Closes the object of StreamReader class and the underlying stream, and releases any system resources associated with the reader.

Peek Returns the next available character but does not consume it.

Read Reads the next character or the next set of character but does not consume it.

ReadLine

Reads a line of characters from the current stream and returns data as a string.

Seek Allows the read/write position to be moved to any position within the file.

Page 85: Csharp3.5

By G.Pavani

using System;using System.IO;Class FileRead{

public void ReadData(){

FileStream fs = new FileStream(“C://Myfile.txt”,FileMode.Open,FileAccess.Read);

StreamReader sr = new StreamReader(fs);sr.BaseStram.Seek(0,SeekOrigin.Begin);string str = sr.ReadLine();while(str!=null){

Console.WriteLine(“{0}”,str);str = sr.ReadLine();

}sr.Close();fs.Close();

}public static void Main(String[] args){

FileRead fr = new FileRead();fr.ReadData();

}}

Page 86: Csharp3.5

By G.Pavani

StreamWritter class

Methods Description

Close Closes the current StreamWriter object and the underlying stream.

Flush Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

Write Writes to the stream.

WriteLine Writes data specific by the overloaded parameters followed by end of line.

The StreamWriter class is inherited from the abstract class TextWritter.

Page 87: Csharp3.5

By G.Pavani

using System;using System.IO;Class FileWrite{

public void WriteData(){

FileStream fs = new FileStream(“C://Myfile.txt”,FileMode.Open,FileAccess.Write);

StreamWriter w = new StreamWriter(fs);Console.WriteLine(“Enter a string”);string str = Console.ReadLine();w.Write(str);w.Flush();w.Close();fs.Close();

}public static void Main(String[] args){

FileWrite fw = new FileWrite();fw.WriteData();

}}

Page 88: Csharp3.5

By G.Pavani

DirectoryInfo Class

Property DescriptionAttributes Gets or sets the attributes associated with the file. This property is

inherited from FileSystemInfo.

Creationtime Gets or sets the creation time of the file.

Exists Gets a boolean value indicating whether the directory exists or not.

Extension Gets a string containing the file extension.

FullName Gets a string containing full path of the directory.

LastAccessTime Gets a string containing time of the directory.

Name Gets a string containing the name of a given file.

Create Create a directory.

CreateSubdirectory

Creates a directory.

Delete Delete a directory.

GetDirectories Returns the directories in the current directory after matching all the criteria.

GetFiles Returns the files in the current directory.

Page 89: Csharp3.5

By G.Pavani

FileInfo Class

Property DescriptionAttributes Gets or sets attributes associated with the file. This property is

inherited from File SystemInfo.

CreationTime Gets or sets Creation time of the current file.

Directory Gets an instance of the directory which the file belongs to.

Exists Gets a boolean indicating whether the file exists or not.

Extension Gets a string containing the file extention.

FullName Gets a string containing the full path of the file.

LastAccessTime

Gets the last accessed time of the file.

LastWriteTime Gets the time of the last written activity of the file.

Length Gets the size of the file.

Name Gets a string contatining the name of a given file.

Create Creates a file.

AppendText Appends a text to the file represented by the FileInfo object

Delete Deletes a file.

Open Opens file.

OpenRead Opens a file in read-only mode.

Page 90: Csharp3.5

By G.Pavani

using System;using System.IO;Class Tester{

public static void Main(){

DirectoryInfo mydir = new DirectoryInfo(@”c:\Windows”);FileInfo[] FileInDir = mydir.GetFiles();foreach(FileInfo file in FileInDir){

Console.WriteLine(“File Name: {} Size: {1} bytes”,file.Name,file.Length);

}}

}

Page 91: Csharp3.5

By G.Pavani

Structures

• A structure in C# is simply a composite data type consisting of a number elements of other types.

• A C# structure is a value type and the instances or objects of a structure are created in stack.

• The structure in C# can contain fields, methods, constants, constructors, properties, indexers, operators and even other structure types.

• The keyword struct can be used to declare a structure.• The general form of a structure declaration in C# is as follows.         

<modifiers> struct <struct_name>{//Structure members}

• Where the modifier can be private, public, internal or public. The struct is the required keyword.

• A struct in C# can contain fields. These fields can be declared as private, public, internal. Remember that inside a struct, we can only declare a field. We can't initialize a field inside a struct. However we can use constructor to initialize the structure fields. 

Page 92: Csharp3.5

By G.Pavani

• A struct in C# can contain fields. These fields can be declared as private, public, internal. Remember that inside a struct, we can only declare a field. We can't initialize a field inside a struct. However we can use constructor to initialize the structure fields.

• struct MyStruct{int x = 20; // Error its not possible to initializeint y = 20; // Error its not possible to initialize}

• A valid C# structure is showing below. using System;struct MyStruct{public int x;public int y;}class MyClient{public static void Main(){MyStruct ms = new MyStruct();ms.x = 10;ms.y = 20;int sum = ms.x + ms.y;Console.WriteLine("The sum is {0}",sum);}}

Page 93: Csharp3.5

By G.Pavani

• A struct can contain static fields, which can be initialized inside the struct. The following example shows the use of static fields inside a struct. 

using System;struct MyStruct{public static int x = 25;public static int y = 50;}class MyClient{public static void Main(){int sum = MyStruct.x + MyStruct.y;Console.WriteLine("The sum is {0}",sum);}}  **static fields can't be accessed by an instance of a struct.

We can access them only by using the struct names.

Page 94: Csharp3.5

By G.Pavani

• A C# struct can also contain methods. The methods can be either static or non-static. But static methods can access only other static members and they can't invoke by using an object of the structure. They can invoke only by using the struct name.

• The methods inside a struct can also be overloaded as like inside a class. For example:using System;struct MyStruct{

static int x = 25;static int y = 50;public void SetXY(int i, int j){

x = i;y = j;

} public void SetXY(int i){

x = i;y = i;

} }class MyClient{

public static void Main(){

MyStruct ms1 = new MyStruct();MyStruct ms2 = new MyStruct();ms1.SetXY(100,200);ms2.SetXY(500);

}}

Page 95: Csharp3.5

By G.Pavani

• A C# struct can declare constructor, but they must take parameters. A default constructor (constructor without any parameters) are always provided to initialize the struct fields to their default values. The parameterized constructors inside a struct can also be overloaded. 

• using System;struct MyStruct{

int x ;int y ;public MyStruct(int i, int j):this(i+j){ }public MyStruct(int i){

x = y = i; }

public void ShowXY(){

Console.WriteLine("The field values are {0} & {1}",x,y); }

}class MyClient{

public static void Main(){MyStruct ms1 = new MyStruct(10,20);ms1.ShowXY();}

}

Page 96: Csharp3.5

By G.Pavani

Similarities and difference between Class and structure in .NET

Similarities:• Both Class and Structures can have methods, variables and objects.• Both can have constructor.• Both are user defined types.Differences:• Structure being value type, the variables cannot be assigned to NULL.

On the other hand, classes being reference type, a class variable can be assigned to NULL.

• Structure is allocated on a stack when instantiated, while Class is allocated on a heap.

• When a method is passed to a class, pass by reference is used. Pass by value is used for struts.

• A class can have a destructor.

Page 97: Csharp3.5

By G.Pavani

Exception Handling• An exception is termed as an abnormal condition encountered by an application

during execution.• Exception handling is the process of providing an alternative path of execution

when the application is unable to execute as desired.• Whenever an error occurs, runtime creats an exception object and sends it to the

program in which the execution occurred. This action is known as throwing an exception.

• All the exceptions are derived from the System.Exception class

Types of Errors:Syntax errors: A syntax error occurs when compiler cannot compile code.This occurs when statements are not constructed properly, keywords are misspelled, or punctuation is omitted.Run-Time Errors: A runtime error occurs when an application attempts to perform an operation, which is not allowed at runtime such as divide by zero.Logical Errors: A logical error occurs when an application compiles and runs properly but does not produce the expected results.

Page 98: Csharp3.5

By G.Pavani

Exception Classes Description

System.IO.IOException Handles I/O errors.

System.IndexOutOfRangeException

Handles errors generated when a method refers to an array element, which is out of its bound.

System.NullReferenceException Handles errors generated during the process of dereferencing a null object.

System.DivideByZeroException Handles errors generated during the process of dividing the dividend with zero.

System.InvalidCastException Handles errors generated during typecasting.

System.OutOfMemoryException Handles memory allocation to the application errors.

Exception Handling

Page 99: Csharp3.5

By G.Pavani

Try Catch Finally

The try Block: Guards' statements that may throw an exception. It defines the scope of the exception-handlers associated with it.

The catch Block: It takes an object of the exception class as a parameter, which refers to the raised exception. When the exception is caught, the statements within the catch block are executed.

The finally Block: It is used to execute a given set of statements, whether an exception is thrown or not thrown.try

{//Statements that may cause an

exception.}catch{

//Error handling code.}finally{

//statements to be executed.}

Page 100: Csharp3.5

By G.Pavani

class Num{

int result;Num(){

result = 0;}public void Divide(int num1, int num2){

try{

result = num1/num2;}catch(DivideByZeroException e){

Console.WriteLine(“Exception catught {0}”,e);}finally{

Console.WriteLine(“Result is {0}”,result);}

}public static void Main(string[] args){

Num obj = new Num();obj.Divide(10,0);Console.ReadLine();

}}

Page 101: Csharp3.5

By G.Pavani

User-Defined Exception

• When we want to catch an exception, do some work to handle the exception and then pass the exception on to the calling code. Such kind of exceptions are known as the user-defined exceptions.

• The Exception must be the base class for all the exceptions in C#.

• User-Defined exception classes are derived from the ApplicationException class.

Page 102: Csharp3.5

By G.Pavani

Class CountZero{

static void Main(string[] args){

Caclulate calc = new Calculate();try{

calc.DoAverage();}catch{

Console.Writeline(“CountIsZeroException: {0}”,e.Message);

}Console.ReadLine();

}}public class CountIsZeroException: ApplicationException{

public CountIsZeroException(string message) : base(message){}

}public class Calculate{

int sume = 0, count=0;float avaerage;public void DoAverage(){

if(count == 0)throw(new CountIsZeroException(“Zero count is

doAverage”));elseaverage = sum/count;

}}

Page 103: Csharp3.5

By G.Pavani

Implementing Threads

• A thread is defined as the exception path of a program.

• A process that is executed using one thread is known as a single-threaded process. Where the process is a running instance of a program. It can perform only one task at a time and have to wait for one task to complete before another task can start.

• To execute more than one task at a time, we have to create mutithreaded process.

Page 104: Csharp3.5

By G.Pavani

The Thread Model

• In single threaded application if the thread is suspended from execution because its waiting for a system resource, the entire program stops executing. This limitation can be overcome by using multithreading, which eliminates event loop with pooling approch.

• In C# we have Thread class which is used to work with threads. The System.Threading.Thread class is used to construct and access individual threads in a mutithreaded application

• The first Thread to be executed in a process is called the Main Thread.

Page 105: Csharp3.5

By G.Pavani

The Main Threadclass MainThreadExample{

public static void Main(string[] args){

Thread Th Thread.CurrentThread;Th.Name =“Main Thread”;Console.WriteLine(“The current thread after name change:{0}”,Th.Name);Console.ReadLine();

}}

A reference to the current thread is obtained by using the variable. The Name parameter is used to set the name of the thread, and the information about the thread is displayed.

Page 106: Csharp3.5

By G.Pavani

Method Description

Start() Starts a thread.

Sleep() Makes the thread to pause for a period of time.

Abort() Terminates the thread.

Suspend() Suspends a thread. It the thread is already suspended it has no effect.

Resume() Resumes the suspended thread.

Class BasicThreadApp{

public static void ChildthreadCall(){

Console.WriteLine(“Child thread started.”);}public static void Main(string[] args){

ThreadStart Childref = new ThreadStart(ChildThreadCall);Console.Writeline(“Main Creating Child Thread”);Thread ChildThread = new Thread(ChildRef);ChildThread.Start();Console.WriteLine(“Main have requested the start of child thread”);Console.Readline();

}}

Page 107: Csharp3.5

By G.Pavani

Class BasicThreadApp{

public static void ChildthreadCall(){

Console.WriteLine(“Child thread started.”);int SleepTime = 5000;Console.Writeline(Sleeping for {0} seconds,SleepTime/1000);Thread.Sleep(SleepTime);Console.WriteLine(‘Waking up !’);

}public static void Main(string[] args){

ThreadStart Childref = new ThreadStart(ChildThreadCall);Console.Writeline(“Main Creating Child Thread”);Thread ChildThread = new Thread(ChildRef);ChildThread.Start();Console.WriteLine(“Main have requested the start of child thread”);Console.Readline();

}}

Page 108: Csharp3.5

By G.Pavani

Thread Life CycleBlocke

d

Runnable

Running

Blocked in

Object’s Lock pool

Blocked in

Object’s Wait Pool

New

Dead

Unblocked Event Block

Lock AquiredSynchronized

wait()

notify()Or interrupted

Alive

start() Scheduler

Page 109: Csharp3.5

By G.Pavani

Multithreading

• Multithreading helps to perform various operations simultaneously and saves time of a user.

• Multithreading allows to achieve multitasking in a program.• Advantages of multithreading

– Improved Performance.– Minimized system resource usage.– Simultaneous access to multiple applications.– Program structure simplification.

• Limitations of Multithreading– Race Condition.– Deadlock Condition.– Lock starvation.

Page 110: Csharp3.5

By G.Pavani

class ThreadSchedule{

public static void ChildThread1(){

Console.WriteLine(“Child Thread 1 started”);Console.WriteLine(“Child Thread- counting 1 to 10”);for(int t=1;t<11;t++){

for(int cnt=0;cnt<100;cnt++){

Console.WriteLine(“.”);}Console.WriteLine(“{0}”,t);

}Console.WriteLine(“Child thread 1 finished”);

}public static void ChildThread2(){

Console.WriteLine(“Child Thread 2 started”);Console.WriteLine(“Child Thread- counting 1 to 10”);for(int t=1;t<11;t++){

for(int cnt=0;cnt<100;cnt++){

Console.WriteLine(“.”);}Console.WriteLine(“{0}”,t);

}Console.WriteLine(“Child thread 2 finished”);

}

public static void Main(){

ThreadStart Child1 = new Threadstart(ChildThread1);ThreadStart Child2 = new Threadstart(ChildThread2);Console.WriteLine(“Main – Creating Child Threads”);Thread Thread1 = new Thread(Child1);Thread Thread2 = new Thread(Child2);Thread1.Start();Thread2.Start();

}}

Page 111: Csharp3.5

By G.Pavani

class ThreadSchedule{

public static void ChildThread1(){

Console.WriteLine(“Child Thread 1 started”);Console.WriteLine(“Child Thread- counting 1 to 10”);for(int t=1;t<11;t++){

for(int cnt=0;cnt<100;cnt++){

Console.WriteLine(“.”);}Console.WriteLine(“{0}”,t);

}Console.WriteLine(“Child thread 1 finished”);

}public static void ChildThread2(){

Console.WriteLine(“Child Thread 2 started”);Console.WriteLine(“Child Thread- counting 1 to 10”);for(int t=1;t<11;t++){

for(int cnt=0;cnt<100;cnt++){

Console.WriteLine(“.”);}Console.WriteLine(“{0}”,t);

}Console.WriteLine(“Child thread 2 finished”);

}

public static void Main(){

ThreadStart Child1 = new Threadstart(ChildThread1);ThreadStart Child2 = new Threadstart(ChildThread2);Console.WriteLine(“Main – Creating Child Threads”);Thread Thread1 = new Thread(Child1);Thread Thread2 = new Thread(Child2);Thread1.Priority=ThreadPriority.Lowest;Thread2.Priority=ThreadPriority.Hightest;Thread1.Start();Thread2.Start();

}}

Page 112: Csharp3.5

By G.Pavani

Delegates

• Delegate in C# allows to dynamically change the reference to the methods in a class.

• A delegate is a reference type variable, which holds the reference to a method. This reference can be changed at runtime.

• Primarily used for implementing events and the call-back methods.

delegate <return-type><delegate-name><parameter-list>

public void DelegateFunction(string ArgValue){

//Method implementation.}

Declaring Delegate

Instantianing Delegate

Page 113: Csharp3.5

By G.Pavani

C# provides support for Delegates through the class called Delegate in the System

namespace.

Delegates are of two types. 1.        Single-cast delegates 2.        Multi-cast delegates

A Single-cast delegate is one that can refer to a single method whereas a Multi-cast

delegate can refer to and eventually fire off multiple methods that have the same

signature.

The signature of a delegate type comprises are the following.

The name of the delegateThe arguments that the delegate would accept as parametersThe return type of the delegate

Delegate Types

Page 114: Csharp3.5

By G.Pavani

class clsDelegate{

public delegate int simpleDelegate (int a, int b); public int addNumber(int a, int b){

return (a+b);}public int mulNumber(int a, int b){

return (a*b);}static void Main(string[] args){

clsDelegate clsDlg = new clsDelegate();simpleDelegate addDelegate = new

simpleDelegate(clsDlg.addNumber);simpleDelegate mulDelegate = new

simpleDelegate(clsDlg.mulNumber);int addAns = addDelegate(10,12);int mulAns = mulDelegate(10,10);Console.WriteLine("Result by calling the addNum

method using a delegate: {0}",addAns);Console.WriteLine("Result by calling the mulNum

method using a delegate: {0}",mulAns);Console.Read();

}}

Page 115: Csharp3.5

By G.Pavani

Implementing a multi-cast delegate

public delegate void TestDelegate();class Test{

public static void Display1(){

Console.WriteLine("This is the first method");}public static void Display2(){

Console.WriteLine("This is the second method");}static void Main(){

TestDelegate t1 = new TestDelegate(Display1);TestDelegate t2 = new TestDelegate(Display2);t1 = t1 + t2; // Make t1 a multi-cast delegatet1(); //Invoke delegateConsole.ReadLine();

}}

Output:This is the first method

This is the second method

Page 116: Csharp3.5

By G.Pavani

Events• An event is an action or occurrence, such as clicks, key

presses, mouse movements, or system generated notifications.

• An application can respond to events when they occur.• The .net Framework event model uses delegates to bind

event notifications with methods known as event handlers.

• The events are declared and raised in a class and associated with the event handlers using delegate with in the same class or other classes.

• Events use the publisher and subscriber model.• A publisher is an object that contains the definition of the

event and the delegate.• A subscriber is an object that wants to accept the event

and provide a handler to the event.

Page 117: Csharp3.5

By G.Pavani

public class Metronome {

public event TickHandler Tick; public EventArgs e = null; public delegate void TickHandler(Metronome m, EventArgs

e); public void Start() {

while (true) {

System.Threading.Thread.Sleep(3000); if (Tick != null) {

Tick(this, e); }

} }

} public class Listener {

public void Subscribe(Metronome m) {

m.Tick += new Metronome.TickHandler(HeardIt);

} private void HeardIt(Metronome m, EventArgs e){

System.Console.WriteLine("HEARD IT"); }

} class Test {

static void Main() {

Metronome m = new Metronome(); Listener l = new Listener(); l.Subscribe(m); m.Start();

} }

Page 118: Csharp3.5

By G.Pavani

//declaring the event handler delegatedelegate void ButtonEventHandler(object source,int clickCount);class Button{//declaring the eventpublic event ButtonEventHandler ButtonClick;//Function to trigger the eventpublic void clicked(int count){Console.WriteLine("\nInside Clicked !!!");//Invoking all the event handlersif (ButtonClick != null) ButtonClick(this,count);}}public class Dialog{ public Dialog(){Button b = new Button();

//Adding an event handlerb. ButtonClick += new ButtonEventHandler(onButtonAction);//Triggering the eventb.clicked(1);b.ButtonClick += new ButtonEventHandler(onButtonAction);b.clicked(1);//Removing an event handlerb.ButtonClick -= new ButtonEventHandler(onButtonAction);b.clicked(1);b.ButtonClick -= new ButtonEventHandler(onButtonAction);b.clicked(1);

}static void Main(){new Dialog();}

Ex:With EventHandeler

Page 119: Csharp3.5

By G.Pavani

//Event Handler functionpublic void onButtonAction(object source,int clickCount){Console.WriteLine("Inside Event Handler !!!");}}

Output:Inside Clicked !!!

Inside Event Handler !!! Inside Clicked !!!

Inside Event Handler !!! Inside Event Handler !!!

Inside Clicked !!! Inside Event Handler !!!

Inside Clicked !!!

Page 120: Csharp3.5

By G.Pavani

A collection in C# is a group of related objects held in a structure .  There are many types of collection defined within the .NET framework, each providing a different structure of objects.  These include collections for holding simple lists, queues and stacks.

A collection is often compared to an array.  Both provide structures that are capable of storing a group of related objects.  However, there are some key differences.

Collections are one-dimensional unlike arrays, which may have many dimensions.  Arrays tend to be fixed structures with a pre-defined size whereas collections can be variable length and can have items inserted at or removed from any position within the set.

Collection consists of queue and stack, sorted lists, bit arrays and associative arrays, also known as dictionaries or collections of key-value pairs.

COLLECTIONS

Page 121: Csharp3.5

By G.Pavani

ARRAYLISTUsing system;Using system.collections;namespace SAMPCOLL{Class arrli{ Public static void main(){ ArrayList a=new ArrayList();a.Add("jan");a.Add("feb");a.Add("march");Console.WriteLine(a[0]);Console.WriteLine(a[1]);Console.WriteLine(a[2]);Console.WriteLine(a.Count);

}}}

Example

JanFebMarch3

ArrayList, a commonly used collection that provides a one-dimensional dynamic array structure. 

COLLECTIONS

Page 122: Csharp3.5

By G.Pavani

HASHTABLEUsing system;Using system.collections;namespace SAMPCOLL{Class hash1{ Public static void main(){Hashtable users = new Hashtable(); // Add some usersusers.Add("andyb", "Andrew Brown");users.Add("alexg", "Alex Green");users.Add("adrienneb", "Adrienne Black"); Console.WriteLine(users.Count);

}}}

Example

3

Hashtable class type of dictionary provides a fast method for retrieving items from the collection by hashing the key into a unique hash code value that is used as an index.

COLLECTIONS

Page 123: Csharp3.5

By G.Pavani

 using System.Collections; namespace StackDemo {    public class TesterStackDemo    {       public void Run()       { Stack intStack = new Stack();           // populate the array           for (int i = 0;i<8;i++)           {             intStack.Push(i*5);           }          // Display the Stack. Console.Write( "intStack values:\t" ); DisplayValues( intStack );           // Remove an element from the stack. Console.WriteLine( "\n(Pop)\t{0}",  intStack.Pop() );           // Display the Stack. Console.Write( "intStack values:\t" ); DisplayValues( intStack );           // Remove another element from the stackConsole.WriteLine( "\n(Pop)\t{0}" intStack.Pop() );// Display the Stack.Console.Write( "intStack values:\t" ); DisplayValues( intStack );          // View the first element in the           // Stack but do not remove.Console.WriteLine( "\n(Peek)   \t{0}",intStack.Peek() );          // Display the Stack Console.Write( "intStack values:\t" );           DisplayValues( intStack );       }

        public static void DisplayValues(            IEnumerable myCollection )        {        foreach (object o in myCollection)            {Console.WriteLine(o);             }}}}}}       [STAThread]       static void Main()       {          TesterStackDemo t = new TesterStackDemo();         t.Run();       }    } }

0<Pop> 35intStack values: 3025201050<Pop> 30intStack values: 2520151050<Peek> 25intStack values: 25201050

COLLECTIONS

Page 124: Csharp3.5

By G.Pavani

Stack

Stack class is generally referred to as LIFO (Last In First Out). Stack in implemented as circular buffer. The various methods of stack class are Push Inserts an object at the top of the Stack Pop Returns and permanently removes the object at the top of the Stack Peek Returns the object at the top of the Stack without removing it Clear Clears the stack by removing all objects from the Stack

Clone Creates a shallow copy of the Stack CopyTo Copies the Stack to an existing one-dimensional Array ToArray Copies the Stack to a new array Contains Determines if an element is present in the Stack Equals Determines if two Object instances are equal ToString Returns a String that represents the current Object GetEnumerator, GetHashCode and GetType are also some of the methods of stack class.

COLLECTIONS

Page 125: Csharp3.5

By G.Pavani

QUEUE

Queue is another collection class in C#. Unlike Stack, it allows the first object entered to pop out first. A queue is referred to as FIFO (First in First Out). The three main methods utilized are Enqueue, Dequeue and Peek.

Peek Returns the object at the beginning of the Queue without removing it.

Dequeue Removes and returns the object at the beginning of the Queue. Enqueue Adds an object to the end of the Queue. Clear, Clone, Contains, CopyTo, ToArray, ToString, Equals, GetEnumerator, GetHashCode, GetType methods are in the Queue.

COLLECTIONS

Page 126: Csharp3.5

By G.Pavani

using System; using System.Collections; public class QueueDemo {   static void showEnq(Queue q, int a) {     q.Enqueue(a);     Console.WriteLine("Enqueue(" + a + ")");      Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " ");      Console.WriteLine();           }    static void showDeq(Queue q) {     Console.Write("Dequeue -> ");     int a = (int) q.Dequeue();     Console.WriteLine(a);      Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " ");         } 

        public static void Main() {     Queue q = new Queue();      foreach(int i in q)       Console.Write(i + " ");      Console.WriteLine();              showEnq(q, 22);     showEnq(q, 65);     showEnq(q, 91);     showDeq(q);     showDeq(q);     showDeq(q);      try {       showDeq(q);     } catch (InvalidOperationException) {       Console.WriteLine("Queue empty.");     }   } }

Example

Enqueue<22>queue: 22Enqueue<65>queue: 22 65Enqueue<91>queue: 22 65 91Dequeue - >22queue: 65 91Dequeue - >65queue: 91Dequeue - >91queue: 22Dequeue -> Query empty

COLLECTIONS

Page 127: Csharp3.5

By G.Pavani

Attributes• An attribute is a declarative tag that is used to convey

information to runtime about the behavior of programmatic elements such as classes, enumerators and assemblies.

• A declarative tag is depicted by square([]) brackets placed above the definition of an element such as class or a method.

• Attributes are used for adding metadata, such as compiler instructions and other information such as comments, description, methods and classes to a program

• Predefined attributes are supplied as a part of the Common Language Runtime(CLR) and are integrated into .net.

• Custom Attributes are attributes that you create according to your requirement.

Page 128: Csharp3.5

By G.Pavani

Using Predefined Attributes

Conditional: Causes conditional compilation of method calls, depending on the specified value such as Debug and Trace.For example, it displays the values of variables, when debugging a code. However, this attribute only determines the action that will occur when a method is called. If conditional compilation of a method is required, the #if and #endif directives are used in code. The methods to which you can apply a conditional attribute are subject to a marked as an override, and the implementation of the method should be from an inherited interface.

Ex:[Conditional(“Debug”)]The preceding statement ensures that the target element, whether a class or a method ensures use of that element in debugging mode only. The other value of this attribute can be:[Conditional(“Trace”)]

Page 129: Csharp3.5

By G.Pavani

WebMethod: Identifies the exposed method in Web service. A Web Service is a Web application that allows you to expose business functionality to other applications. Furthermore, the various properties of this attribute enable you to configure the behaviour of the exposed method.

The following code is the example of using WebMethod attribute:[WebMethod(Description = “Converts temperature from Fahrenheit to Celsius.”)]

public double TempConvert(double myTemp){

return ((myTemp-32)*5)/9;}

The preceding code provides an exposed method of a Web service which converts temperature from Fahrenheit to Celsius. The WebMethod attribute definition above TempConvert() method tells the compiler that it is an exposed method and the Description property of the WebMethod attribute provides information about working of the Tempconvert() method.

Using Predefined Attributes

Page 130: Csharp3.5

By G.Pavani

Using Predefined Attributes

DllImport: Calls an unmanaged code in programs developed outside .net environment. An example of such a program is the standard C program compiled into DLL files. By using the DllImport attribute, the unmanaged code residing in dynamic-link libraries(DDLs) can be called from the managed C# environment.

The following code is an example of using DllImport attribute:using System;System.Runtime.InteropServices;class GenerateBeeps{

[DllImport(.kernel32.dll)]public static extern bool Beep(int f, int d); public static void Main(){

Beep(1000,111);}

}The preceding code uses the Beep() method defined in kernel32.dll and parameters f and d signify the frequency and duration of beep to generate.

Page 131: Csharp3.5

By G.Pavani

Using Predefined AttributesObsolete: Enables you to inform the compiler to discard a piece of target element such as a method of a class.For eg: when a new method is being used in a class but you still want to retain the old method in that class, as a developer, you can mark the old method as obsolete. You mark the old method as obsolete by displaying a message starting that instead of the old method, the new method should be used.Ex:using System;Public class MyClass{

[Obsolete(“Don’t use the A() method, instead use B() method”, true)]static void A() {}static void B() {}public static void Main(){

A();}

}In the preceding code, the first parameter is string, which contains the message. The second parameter tells the compiler to treat the use of the element as an error. The default value is false, which means compiler generates a warning for this.

Page 132: Csharp3.5

By G.Pavani

Reflections

• Reflection is used in the process of obtaining type information at runtime. The classes that give access to the metadata of a running program are in System.Reflection.

• Reflections is generally used for:– Viewing metadata: allows viewing examining attribute information

from the code at runtime.– Performing type discovery: allows examining the various types in

an assembly and instantiate those types.– Late binding to methods and properties: allows the developer to

call properties and methods on dynamically instantiated objects using discovery.

– Reflection emit: allows to create new types at runtime and then to use those types to perform tasks.

Page 133: Csharp3.5

By G.Pavani

Using System; using System.Reflection; public class MyClass {

public virtual int AddNumb(int numb1,int numb2) {

int result = numb1 + numb2; return result;

} } class MyMainClass {

public static int Main() {

Console.WriteLine ("\nReflection.MethodInfo"); // Create MyClass object MyClass myClassObj = new MyClass(); // Get the Type information. Type myTypeObj = myClassObj.GetType(); // Get Method Information. MethodInfo myMethodInfo =

myTypeObj.GetMethod("AddNumb"); object[] mParam = new object[] {5, 10}; // Get and display the Invoke method. Console.Write("\nFirst method - " + myTypeObj.FullName +

" returns " + myMethodInfo.Invoke(myClassObj, mParam) + "\n"); }

}

Page 134: Csharp3.5

By G.Pavani

Questions?

Page 135: Csharp3.5

By G.Pavani