session 9_tp 5 [read-only]
TRANSCRIPT
Session 5
Advanced C# Concepts - I
C# Simplified / Session 5 / 2 of 45
ReviewApart 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.
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.
C# Simplified / Session 5 / 4 of 45
Objectives
Discuss and create AssembliesExplain Private and Shared AssembliesDiscuss VersioningDiscuss ReflectionsDiscuss CollectionsExplain Error Handling
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
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 functionalityA manifest that contains information, which describes the assembly
C# Simplified / Session 5 / 7 of 45
ManifestA 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
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>
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
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
C# Simplified / Session 5 / 11 of 45
Namespaces vs. Assembly
Difference between Namespace & Assembly -
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
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
C# Simplified / Session 5 / 14 of 45
Global Assembly Folder
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)
C# Simplified / Session 5 / 16 of 45
Access ModifiersAccess 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 modifierThe internal modifier can be used to specify accessibility at the assembly level instead of the class level
C# Simplified / Session 5 / 17 of 45
Internal access modifier
C# Simplified / Session 5 / 18 of 45
Versioning
All assemblies must have a version numberAssemblies having the same name but different version numbers can coexist in the same application.
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
C# Simplified / Session 5 / 20 of 45
Solving “DLL Hell” ProblemIn 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 hadto be modifiedHowever, 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
C# Simplified / Session 5 / 21 of 45
Reflection (1)Used to retrieve information about an object at runtimeThe Type class is the base of all reflection information for an objectTwo methods to retrieve the Type object –
typeof()GetType()
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
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;}}}
C# Simplified / Session 5 / 24 of 45
Reflection – Methods of Type
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();
C# Simplified / Session 5 / 26 of 45
Reflection – GetMembers Outputforeach (MemberInfo memInfo in memInfoArray)
{Console.WriteLine (memInfo);
}return 0;
} }
}
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
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); }}
C# Simplified / Session 5 / 29 of 45
ArrayList ClassArrayList 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
C# Simplified / Session 5 / 30 of 45
Arraylist Class – Contd…
Used to specify an element at a specific index position in the ArrayList
Item
Used to specify whether an ArrayList has a fixed size
IsFixedSize
Used to specify whether an ArrayList is read-only
IsReadOnly
Indicates the number of elements actually present in an ArrayList
Count
Used to specify the number of elements in as ArrayList
Capacity
DescriptionProperty
Properties of ArrayList class are as follows
C# Simplified / Session 5 / 31 of 45
Arraylist Class – ContdPublic methods of ArrayList class are as follows
Specifies the positional index of the last occurrence of the given element in the ArrayList.
LastIndexOf
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.
IndexOf
Used to copy the entire contents of an ArrayList or a part of it to single-dimensional Array
CopyTo
Checks whether the given element is present in the ArrayList
Contains
Removes all the elements from the specified ArrayListClear
Used to add an element at the end of an ArrayListAdd
DescriptionMethod
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" );
C# Simplified / Session 5 / 33 of 45
ArrayList Class - ExampleConsole.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();}}
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
C# Simplified / Session 5 / 35 of 45
Exceptions – Contd…The .NET framework provides us with a large range of exception classes that store information regarding exceptions
C# Simplified / Session 5 / 36 of 45
Try & catch blocks
Helps in handling raised exceptions
C# Simplified / Session 5 / 37 of 45
More on catch blocksC# allows the usage of more than one catch block
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
C# Simplified / Session 5 / 39 of 45
Using throw
The throw statement allows you to raise custom exceptions
C# Simplified / Session 5 / 40 of 45
Using FinallyThe code in this block is executed irrespective of whether an exception was raised or not
C# Simplified / Session 5 / 41 of 45
try…..catch - Exampleusing 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;}
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("");
}
C# Simplified / Session 5 / 43 of 45
try….catch – Example Outputfinally{Console.WriteLine ("finally block");if (quotient != 0){Console.WriteLine("The Integer Quotient of 50 divided by {0} is {1}", userInput, quotient);
}}}}
C# Simplified / Session 5 / 44 of 45
SummaryAn 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 AssembliesThe version number of an assembly is represented as a four-part number in the following format: <Major version>.< Minor version >.<Revision>.<Build Number>
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.