Top Banner
Session 5 Advanced C# Concepts - I
45
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Session 9_TP 5

Session 5

Advanced C# Concepts - I

Page 2: Session 9_TP 5

C# Simplified / Session 5 / 2 of 45

Review Apart from avoiding naming conflicts, namespaces are also

elements designed to help organize the code. Namespaces can be nested. Namespaces are implicitly public.

A fully qualified name is the name of the class prefixed by the namespace within which it is contained and the dot operator.

With ‘using namespace directives’, we can employ classes outside their namespaces without using their qualified names. The using namespace directives must be declared before any member declarations.

‘using alias directives’ can be deployed to pull out and bring into scope one component (a class or a struct) from a namespace.

The Base Class Library is a collection of pre-written code that can be incorporated easily and used in our applications.

Page 3: Session 9_TP 5

C# Simplified / Session 5 / 3 of 45

Review Contd… The System.String class provides methods for

manipulating strings.

The System.Array class provides methods for manipulating arrays.

We can use the System.Threading namespace to implement multi-threading into our programs.

The System.IO namespace provides plenty of classes for file/stream input/output.

Page 4: Session 9_TP 5

C# Simplified / Session 5 / 4 of 45

Objectives

Discuss and create Assemblies Explain Private and Shared

Assemblies Discuss Versioning Discuss Reflections Discuss Collections Explain Error Handling

Page 5: Session 9_TP 5

C# Simplified / Session 5 / 5 of 45

Assemblies

The sharing is taken care of automatically using certain commands.

An assembly is a means of reusing code without using any complex syntax

Page 6: Session 9_TP 5

C# Simplified / Session 5 / 6 of 45

Assemblies – Contd… An assembly consists of two main

elements A set of types and resources that form a

logical unit of functionality A manifest that contains information, which

describes the assembly Set of Types andResources

Manifest

An Assembly

Page 7: Session 9_TP 5

C# Simplified / Session 5 / 7 of 45

Manifest A manifest is the metadata that

describes how elements in an assembly are related

Contains information about the other assemblies on which they depend for proper functioning

Contains identity of an assembly Contains details of all the types and

resources defined in the assembly

Page 8: Session 9_TP 5

C# Simplified / Session 5 / 8 of 45

Creating Assemblies To create an assembly use the

following command-

The following command creates an assembly called “array.dll”

C:\> csc /out:<assembly name>/target:library <filename1 filename2..>

C:\> csc /out: array.dll /target:library array1.cs>

Page 9: Session 9_TP 5

C# Simplified / Session 5 / 9 of 45

After an assembly is created, it can be referenced from an executable.

To create an executable from a .cs file use the following command

Creating Executables

The following command creates a .exe file from a .cs file

C:\>csc /out<executable name> /targetexe <filename1 filename2.cs>

C:\>csc /out trial.exe /targetexe trial1.cs

Page 10: Session 9_TP 5

C# Simplified / Session 5 / 10 of 45

The following command is used to reference an assembly

Referencing an Assembly

The following command creates an executable called trial.exe from the source file trial1.cs while referencing an assembly called newtrial.dll

C:\>csc /out<executable name> /target.exe /r<assembly name1;assembly name2..><filename1 filename2..>

C:\>csc /out trial.exe /target.exe /r newtrial.dll trial1.cs

Page 11: Session 9_TP 5

C# Simplified / Session 5 / 11 of 45

Namespaces vs. Assembly Difference between Namespace &

Assembly -

Page 12: Session 9_TP 5

C# Simplified / Session 5 / 12 of 45

Types of Assemblies - Private Assemblies can be of two types: private

and shared

By default, a C# program is compiled to a private assembly

Needs to be placed in the same folder as the application

Assembly name should be unique within the application

Page 13: Session 9_TP 5

C# Simplified / Session 5 / 13 of 45

Types of Assemblies - Shared

Can be shared across various applications

Assembly name should be unique across all applications using the assembly

Placed in the Global Assembly Cache

Page 14: Session 9_TP 5

C# Simplified / Session 5 / 14 of 45

Global Assembly Folder

Page 15: Session 9_TP 5

C# Simplified / Session 5 / 15 of 45

Global Assembly Folder There are two ways by which an

assembly can be installed into the global assembly cache Using Microsoft Windows Installer 2.0.

Using the Global Assembly Cache tool (Gacutil.exe)

Page 16: Session 9_TP 5

C# Simplified / Session 5 / 16 of 45

Access Modifiers Access modifiers define the level of

access that certain blocks of code have, to class members like its methods and properties

C# introduces a new access modifier known as the internal access modifier

The internal modifier can be used to specify accessibility at the assembly level instead of the class level

Page 17: Session 9_TP 5

C# Simplified / Session 5 / 17 of 45

Internal access modifier

Page 18: Session 9_TP 5

C# Simplified / Session 5 / 18 of 45

Versioning

All assemblies must have a version number

Assemblies having the same name but different version numbers can coexist in the same application.

Page 19: Session 9_TP 5

C# Simplified / Session 5 / 19 of 45

Versioning

The version number of an assembly is represented as a four-part number in the following format

Page 20: Session 9_TP 5

C# Simplified / Session 5 / 20 of 45

Solving “DLL Hell” Problem In the previous versions of Microsoft Windows operating

systems, two DLL files with the same name could not be used in a single process

DLL file needed to be upgraded and the registry entry for it had to be modified

However, other applications using the older DLL file may still be searching for that DLL file

This is because the registry entries of those applications may not have been updated with the new DLL file.

This situation is known as “DLL Hell”. The Windows 2000 operating system is capable of

loading two assemblies with the same name but different version numbers.

Therefore, it is possible to have a new version of that file, while still using the same name for the newer version

Page 21: Session 9_TP 5

C# Simplified / Session 5 / 21 of 45

Reflection (1) Used to retrieve information about

an object at runtime The Type class is the base of all

reflection information for an object Two methods to retrieve the Type

object – typeof() GetType()

Page 22: Session 9_TP 5

C# Simplified / Session 5 / 22 of 45

Reflection - Exampleusing System;namespace RefDemo{public class ReflectionDemo{ public int addition(int first, int second) { return first+second; }

public static int Main(){ Type refType= typeof(ReflectionDemo); //Class Reference ReflectionDemo objRef =new ReflectionDemo(); Type objType = objRef.GetType(); // Object Reference

Page 23: Session 9_TP 5

C# Simplified / Session 5 / 23 of 45

Reflection - OutputConsole.WriteLine ("The type of objRef is : {0} ", objType);Console.WriteLine ("The type of ReflectionDemo is : {0}", refType);Console.WriteLine ("The Namespace of ReflectionDemo is : {0} ", refType.Namespace);return 0;}}}

Page 24: Session 9_TP 5

C# Simplified / Session 5 / 24 of 45

Reflection – Methods of Type

Page 25: Session 9_TP 5

C# Simplified / Session 5 / 25 of 45

Reflection – GetMembersnamespace Reflection_Example{ using System; using System.Reflection; public class RefExample { private int intSum; public void addition(int intA, int intB) { intSum= intA + intB; } public static int Main() { Type refType= typeof(RefExample); MemberInfo[] memInfoArray = refType.GetMembers();

Page 26: Session 9_TP 5

C# Simplified / Session 5 / 26 of 45

Reflection – GetMembers Output

foreach (MemberInfo memInfo in memInfoArray) { Console.WriteLine (memInfo); } return 0; } }}

Page 27: Session 9_TP 5

C# Simplified / Session 5 / 27 of 45

Collections Collections are general-purpose

datatypes, that provide us with a store, and act upon them collectively

Hashtable class allows us to store data as a collection of keys and value pairs, which are organized depending on the hash code of the key

Page 28: Session 9_TP 5

C# Simplified / Session 5 / 28 of 45

Collections - Example

using System.Collections;class HashDemo{ static void Main() { Hashtable listOfStudents = new Hashtable(); listOfStudents.Add ("Sam", "8605130"); listOfStudents.Add("Smith", "8604292"); listOfStudents.Add("Tom", "8604292"); System.Console.WriteLine ("The number of students in the school are {0} ", listOfStudents.Count); }}

Page 29: Session 9_TP 5

C# Simplified / Session 5 / 29 of 45

ArrayList Class ArrayList is actually a refined version of

an array that offers some features that are offered in most Collections classes but are not in the Array class

The capacity or the number of elements of an Array is fixed; on the other hand the capacity of an ArrayList can be expanded dynamically as per the requirement

A range of elements can be inserted or removed at one point of time with the help of methods provided by ArrayList

Page 30: Session 9_TP 5

C# Simplified / Session 5 / 30 of 45

Arraylist Class – Contd…

Property DescriptionCapacity Used to specify the number of

elements in as ArrayList

Count Indicates the number of elements actually present in an ArrayList

IsReadOnly Used to specify whether an ArrayList is read-only

IsFixedSize Used to specify whether an ArrayList has a fixed size

Item Used to specify an element at a specific index position in the ArrayList

Properties of ArrayList class are as follows

Page 31: Session 9_TP 5

C# Simplified / Session 5 / 31 of 45

Arraylist Class – ContdPublic methods of ArrayList class are as follows

Method Description

Add Used to add an element at the end of an ArrayList

Clear Removes all the elements from the specified ArrayList

Contains Checks whether the given element is present in the ArrayList

CopyTo Used to copy the entire contents of an ArrayList or a part of it to single-dimensional Array

IndexOf Specifies the positional index of the first occurrence of the given element in the ArrayList. It is important to note here that the positional index is zero-based.

LastIndexOf Specifies the positional index of the last occurrence of the given element in the ArrayList.

Page 32: Session 9_TP 5

C# Simplified / Session 5 / 32 of 45

ArrayList Class - Exampleusing System;using System.Collections;public class ArrlistDemo{public static void Main() { ArrayList myArrLst = new ArrayList(); Console.WriteLine ("Enter names of 5 countries below:"); for(int i = 0;i <= 4;i++) { Console.Write ("Enter country {0} :", i+1); string str1 = Console.ReadLine(); myArrLst.Add(str1); } Console.WriteLine( "Information about Countries" );

Page 33: Session 9_TP 5

C# Simplified / Session 5 / 33 of 45

ArrayList Class - Example Console.WriteLine( "\tCount:{0}", myArrLst.Count );Console.WriteLine( "\tCapacity: {0}", myArrLst.Capacity );Console.WriteLine ("The contents of the arraylist are as follows");System.Collections.IEnumerator myEnumerator = myArrLst.GetEnumerator();while ( myEnumerator.MoveNext() ) Console.Write( "\n{0}", myEnumerator.Current ); Console.ReadLine();}}

Page 34: Session 9_TP 5

C# Simplified / Session 5 / 34 of 45

Exceptions A program will crash rarely if it has

been programmed to recover from situations that may result in an error

Exceptions are used to anticipate and trap errors that may result in crashing a program

Page 35: Session 9_TP 5

C# Simplified / Session 5 / 35 of 45

Exceptions – Contd…

System.Exception

System.SystemException System.ApplicationException

ArithmeticException

Data.DataException

ArgumentException

FormatException

IO.IOException

………..

Reflection.TargetException

Reflection.InvalidCriteriaException

………..

DivideByZeroException

OverflowException

IO.EndOFStreamException

FileLoadException

………..

The .NET framework provides us with a large range of exception classes that store information regarding exceptions

Page 36: Session 9_TP 5

C# Simplified / Session 5 / 36 of 45

Try & catch blocks

Helps in handling raised exceptions

Page 37: Session 9_TP 5

C# Simplified / Session 5 / 37 of 45

More on catch blocks

C# allows the usage of more than one catch block

Page 38: Session 9_TP 5

C# Simplified / Session 5 / 38 of 45

General catch blockGeneral catch block is the one that can trap just about any type of exception

one try can have only one general catch block

Page 39: Session 9_TP 5

C# Simplified / Session 5 / 39 of 45

Using throw

The throw statement allows you to raise custom exceptions

Page 40: Session 9_TP 5

C# Simplified / Session 5 / 40 of 45

Using Finally

The code in this block is executed irrespective of whether an exception was raised or not

Page 41: Session 9_TP 5

C# Simplified / Session 5 / 41 of 45

try…..catch - Example

using System;class ExceptionDemo{ static void Main() { int dividend = 50; int userInput = 0; int quotient = 0; Console.WriteLine ("Enter a number : "); try { userInput = Convert.ToInt32 (Console.ReadLine()); quotient = divident /userInput; }

Page 42: Session 9_TP 5

C# Simplified / Session 5 / 42 of 45

try….catch - Example

catch (System.FormatException excepE) { Console.WriteLine (excepE); } catch (System.DivideByZeroException excepE) { Console.WriteLine ("catch block"); Console.WriteLine (excepE); Console.WriteLine(""); }

Page 43: Session 9_TP 5

C# Simplified / Session 5 / 43 of 45

try….catch – Example Output

finally{ Console.WriteLine ("finally block"); if (quotient != 0) { Console.WriteLine("The Integer Quotient of 50 divided by {0} is {1}", userInput, quotient); }}}}

Page 44: Session 9_TP 5

C# Simplified / Session 5 / 44 of 45

Summary An assembly consists of:

A set of types and resources that form a logical unit of functionality.

A manifest containing information that describes the assembly.

We can deploy classes within the same namespace into different assemblies, and classes within different namespaces into one assembly.

Assemblies are of two types: Private Assemblies and Shared Assemblies

The version number of an assembly is represented as a four-part number in the following format: <Major version>.< Minor version >.<Revision>.<Build Number>

Page 45: Session 9_TP 5

C# Simplified / Session 5 / 45 of 45

Summary Contd… The System.Reflection namespace contains around forty

classes and interfaces that can be employed to get information about an object.

Collections are datatypes that provide us with a way to store and collectively act upon data.

Exceptions are raised by the runtime when an error occurs. The try and catch block helps in handling raised

exceptions. Using the Throw statement, we can either throw a system

exception, or our own custom exception. The statements in the Finally block are executed

regardless of the control flow.