C# - Part 1

  • 975 views
Uploaded on

C# training slide

C# training slide

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
975
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
70
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • decimal bankBalance = 3433.20; // ERROR! This code causes an error because the C# compiler assumes than any literal number with a decimal point is a double, unless otherwise specified. You specify the type of the literal by appending a suffix, as shown in the following example:decimal bankBalance = 3433.20M;A literal is a value that has been hard-coded directly into your source.For example:string x = "This is a literal"; int y = 2; // so is 2, but not y int z = y + 4; // y and z are not literals, but 4 is Some literals can have a special syntax, so you know what type the literal is://The 'M' in 10000000M means this is a decimal value, rather than int or double. varaccountBalance = 10000000M;
  • C# has four types of operators: unary, binary, ternary, and afew others that don’t fit into a category.
  • C provides two sytles of flow control:BranchingLoopingBranching is deciding what actions to take and looping is deciding how many times to take a certain action.Branching:Branching is so called because the program chooses to follow one branch or another.
  • Difference between readonly and constant.
  • Array is the collection of values of the same data typethe variables in an array is called array elementsArray is a reference type data typeThe array structure in System's MemoryArray list is a class .when you want to access the elements of an array through its index value location in an array,use an ArrayList.The use of the arraylist is an alternative to the use of the array.The Methods Of ArrayList class are1)Add2)Remove3)Clear4)Insert5)TrimToSize6)Sort7)Reverse->another difference between array list and array is arraylist can dynamically increase or decrease its size were as array size is constant

Transcript

  • 1. Md. Mahedee Hasan Senior Software Engineer LEADS Corporation Limited
  • 2.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 3.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 4.  C# is intended to be a simple, modern, general- purpose, object-oriented programming language  It is very sophisticated programming language  It is developed by Microsoft with its .NET initiatives  The language is intended for use in developing Software Components
  • 5.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 6.  Program execution begins at Main()  The using keyword refers to resources in the .NET framework class library  Statements are commands that perform actions  A program is made up of many separate statement  Statement are separated by a semicolon  Braces are used to group statement
  • 7.  Use indentation to indicate enclosing statements  C# is case sensitive  White space is ignored  Indicate single line comment by using //  Indicate multiple line comment by using /*and*/
  • 8.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 9.  Types are used to declare variables  Variables store different kinds of data  Predefined types are those provided by C# and .NET framework  You can also defined your own  Variable must be declared before you can use them
  • 10. Predefined type Definition Bytes Byte Integer between 0 and 255 1 Sbyte Integer between -128 and 127 1 Short Integer between -32768 and 32767 2 Ushort Integer between 0 and 65535 2 Int Integer between -2147483648 and 2147483647 4 Uint Integer between 0 and 4294967295 4 Long Integer between -9223372036854775808 and 9223372036854775807 8 Ulong Integer between 0 and 18446744073709551615 8 Bool Boolean value: true or false 1 Float Single-precision floating point value (non-whole number) 4 Double Double-precision floating point value 8 Decimal Precise decimal value to 28 significant digits 12 Object Base type of all other types N/A Char Single Unicode character between 0 and 65535 2 String An unlimited sequence of Unicode characters N/A
  • 11.  A variable is a storage location for a particular type  Declaring  Assign a type  Assign a name  End with a semicolon  Ex. int noOfUser; string firstName;  Initializing  Use assignment operator  Assign a value  End with a semicolon  Ex. string firstName = “Mahedee”;  Assigning literal variable  Add a type suffix  Ex. decimal deposit = 50000M;
  • 12.  string str = “Hello world”; //Hello world  Literal string  string str = “”Hello””; //”Hello”  Escape character  string str = “HellonWorld”; a new line is added between Hello and World  Using verbatim string  string str = @”Hellon”; Hellon
  • 13.  Declare using const keyword and type  You must assign a value at the time of declaration  Examples  const double pi = 3.14;  const int earthRadius = 6378;
  • 14.  User defined data type  Purpose of enumeration type is to use constant values  Process to create enumeration type  Create an enumeration type  Declare variable of that type  Assign values to those variables
  • 15.  Defining enumeration types enum BluechipTeam{ Azad, Mahedee, Sarwar, Jamil }  Using enumeration types BluechipTeam aMember = BluechipTeam.Mahedee;  Displaying the variables Console.WriteLine(aMember);
  • 16.  Implicit  Performed by the compiler on operations that are guaranteed not to truncate information int x = 123456; // int is a 4-byte integer long y = x; // implicit conversion to a long  Explicit  Where you to explicitly ask the compiler to perform a conversion that otherwise could lose information int x = 500; short z = (short) x; // explicit conversion to a short, z contains the value 500
  • 17.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 18.  An expression is a sequence of operators and operands  The purpose of writing an expression is to perform an action and return a value
  • 19.  Expressions are evaluated according to operator precedence  Example: 10 + 20 / 5 (result is 14)  Parenthesis can be used to control the order of evaluation.  Ex. (10 + 20) / 5 (result is 6)  Operator precedence is also determined by associativity  Binary operators are left associative i.e evaluated from left to right.  Assignment and conditional operators are right associative i.e evaluated from right to left
  • 20.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 21.  Setting break point
  • 22.  Step In = F11 = Step into a Method  Step Out = Shift + F11 = Steps up and out of a method back to the caller  Step Over = F10 = Steps past a method to the next statement  Stop Debugging = Shift + F5 = Stops a debugging session
  • 23.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 24.  A conditional statement allows you to control the flow of your application by selecting the statement that is executed, based on the value of a Boolean expression.
  • 25.  if statement if ( sales > 10000 ) { bonus += .05 * sales; }  if else statement if ( sales > 10000 ) { bonus += .05 * sales; } else { bonus = 0; }  if else if satement if ( sales > 10000 ) { bonus += .05 * sales; } else if ( sales > 5000 ) { bonus = .01 * sales; } else { bonus = 0; if ( priorBonus == 0 ) { // Schedule a Meeting; } }
  • 26.  Switch statements are useful for selecting one branch of execution from a list of mutually-exclusive choices. switch( favoriteAnimal ) { case Animal.Antelope: // herbivore-specific statements break; case Animal.Elephant: // herbivore-specific statements break; case Animal.Lion: // carnivore-specific statements break; case Animal.Osprey: // carnivore-specific statements break; default: //default statemennt }
  • 27.  C# provides several looping mechanisms, which enable you to execute a block of code repeatedly until a certain condition is met  Looping mechanism  for loop.  while loop.  do loop.
  • 28.  Use when you know how many times you want to repeat the execution of the code  Syntax: for (initializer; condition; iterator) { statement-block }  Example: for ( int i = 0; i < 10; i++ ) { Console.WriteLine( "i = {0}",i ); }
  • 29.  A Boolean test runs at the start of the loop and if tests as False, the loop is never executed.  The loop executed until the condition becomes false.  Syntax: while (true-condition) { statement-block }  Example while ( i <= 10 ) { Console.WriteLine(i++); }
  • 30.  The continue keyword to start the next loop iteration without executing any remaining statements  The break keyword is encountered, the loop is terminated  Example: int i = 0; while ( true ) { i++; if(i>5) continue; if(i>= 10) break; Console.WriteLine(i); }
  • 31.  Executes the code in the loop and then performs a Boolean test. If the expression as true then the loop repeats until the expression test as false  Syntax: do { statements } while (boolean-expression);  Example: int i = 1; do { Console.WriteLine("{0}", i++); } while ( i <= 10 );
  • 32.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 33.  Classes  Like blueprint of objects  Contain methods and data  Objects  Are instances of class  Create using the new keyword  Have actions
  • 34.  Value Types  Directly contain data  Stored on the stack  Must be initialized  Cannot be null  An int is a value type  Example: int a; a = 15; a 15
  • 35.  Contain a reference to the data  Stored on the heap  Declared using new key word  .NET garbage collection handles destruction  A class is a reference type  Example: EmployeeInfo c; c * 15
  • 36.  Boxing  Treat value types like reference types  Example: object boxedValue = (object) x;  Unboxing  Treat reference types like value types  Example: int y = (int) boxedValue;
  • 37.  How to define class public class Investor { public string firstName; public string lastName; public double purchasePower; }  How to create an object  Example: Investor objInvestor = new Investor();  How to access class variable  Example: objInvestor.firstName = “Mahedee”;
  • 38.  Declaring namespace namespace Bluchip { public class Investor { public string firstName; public string lastName; public double purchasePower; } }  Nested namespaces namespace Bluchip { namespace InvestorSetup { public class Investor { //to do } } }  The using namespace  using Bluechip  using Bluechip.InvestorSetup
  • 39.  Access modifiers are used to define the accessibility level of class members  public: Access not limited  private: Access limited to the containing class  internal: Access limited to this program  protected: Access limited to the containing class and to types derived from the containing class  protected internal: Access limited to the containing class, derived classes or to members of this program.
  • 40.  A method is a class member that is used to define the actions  Declare Mathod: class Lion { private int weight; public bool IsNormalWeight() { if ( ( weight < 100 ) || ( weight > 250 ) ) { return false; } return true; } public void Eat() { } public int GetWeight() { return weight; } }  Invoke method: Lion bigLion = new Lion(); if ( bigLion.IsNormalWeight() == false ) { Console.WriteLine("Lion weight is abnormal"); }
  • 41.  Passing by value class Lion { private int weight; public void SetWeight( int newWeight ) { weight = newWeight; } } Lion bigLion = new Lion(); int bigLionWeight = 200; bigLion.SetWeight( bigLionWeight );
  • 42.  Passing by reference  Using the ref keyword  Definite assignment  Using out parameter keyword  Allow you to initialize variable in method  Use if you want a method to modify or return multiple values  Achieve this by passing the method a reference
  • 43. class Zoo { private int streetNumber = 123; private string streetName = "High Street"; private string cityName = "Sammamish"; public void GetAddress(ref int number, ref string street, ref string city) { number = streetNumber; street = streetName; city = cityName; } }
  • 44. class ClassMain { static void Main(string[] args) { Zoo localZoo = new Zoo(); // note these variables are not initialized int zooStreetNumber; string zooStreetName; string zooCity; localZoo.GetAddress(out zooStreetNumber, out zooStreetName, out zooCity); Console.WriteLine(zooCity); // Writes "Sammamish" to a console } }
  • 45.  When you pass a reference type to a method, the method can alter the actual object. using System; namespace LearningCSharp { class MainClass { static void Main(string[] args) { Zoo myZoo = new Zoo(); Lion babyLion = new Lion(); myZoo.AddLion( babyLion ); } } class Lion { public string location; } class Zoo { public void AddLion( Lion newLion ) { newLion.location = "Exhibit 3";} } }
  • 46.  Method overloading is a language feature that enables you to create multiple methods in one class that have the same name but that take different signatures  By overloading a method, you provide the users of your class with a consistent name for an action while also providing them with several ways to apply that action.  Overloaded methods are a good way for you to add new functionality to existing code.
  • 47. class Zoo { public void AddLion( Lion newLion ) { // Place lion in an appropriate exhibit } public void AddLion( Lion newLion, int exhibitNumber ) { // Place the lion in exhibitNumber exhibit } } Zoo myZoo = new Zoo(); Lion babyLion = new Lion(); myZoo.AddLion( babyLion ); myZoo.AddLion( babyLion, 2 );
  • 48.  Constructors are special methods that implement the actions that are required to initialize an object.  Instance constructors are special type methods that implements the actions required to initialize an object.  Have the same name as the name of the class  Default constructor takes no parameter
  • 49. public class Lion { private string name; public Lion() { Console.WriteLine("Constructing Lion"); } public Lion( string newLionName ) { this.name = newLionName; } } Lion babyLion = new Lion(); Console.WriteLine("Made a new Lion object"); Output: Constructing Lion Made a new Lion object
  • 50.  When you use the readonly modifier on a member variable, you can only assign it a value when the class or object initializes, either by directly assigning the member variable a value, or by assigning it in the constructor.  Use the readonly modifier when a const keyword is not appropriate because you are not using a literal value—meaning that the actual value of the variable is not known at the time of compilation.
  • 51. class Zoo { private int numberAnimals; public readonly decimal admissionPrice; public Zoo() { // Get the numberAnimals from some source... if ( numberAnimals > 50 ) { admissionPrice = 25; } else { admissionPrice = 20; } } }
  • 52.  Create multiple constructor that have same name but different signatures  It is often useful to overload a constructor to allow instances to be created in more than one way.
  • 53. public class Lion { private string name; private int age; public Lion() : this ( "unknown", 0 ) { Console.WriteLine("Default {0}", name); } public Lion( string theName, int theAge ) { name = theName; age = theAge; Console.WriteLine("Specified: {0}", name); } } Lion adoptedLion = new Lion();
  • 54.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 55.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 56.  Static members belong to the class, rather than an instance.  Static constructors are used to initialize a class.  Initialize before an instance of the class is created.  Shared by all instance of the class  Classes can have static members, such as properties, methods and variables.  Because static members belong to the class, rather than an instance, they are accessed through the class, not through an instance of the class.
  • 57. using System; namespace StaticExample { class ZooDemo { static void Main(string[] args) { Console.WriteLine( "Family: {0}", Lion.family ); Console.ReadLine(); } } class Lion { public static string family = "felidae"; } } Output: fedilae
  • 58.  Instance constructors are used to initialize an object  Static constructors are used to initialize a class  Will only ever be executed once  Run before the first object of that type is created.  Have no parameter  Do not take an access modifier  May co-exist with a class constructor
  • 59. using System; namespace StaticConstructor { class RandomNumberGenerator { private static Random randomNumber; static RandomNumberGenerator() { randomNumber = new Random(); } public int Next() { return randomNumber.Next(); } } class Class1 { static void Main(string[] args) { RandomNumberGenerator r = new RandomNumberGenerator(); for ( int i = 0; i < 10; i++ ) { Console.WriteLine( r.Next() ); } } } }
  • 60.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 61. Structure Design Object Oriented Design Process centered Object centered Reveals data Hide data Single unit Modular unit One time use Reusable Ordered algorithm No ordered algorithm
  • 62.  Programs are easier to design because objects reflect real-world items.  Applications are easier for users because data - they do not need is hidden.  Objects are self-contained units.  Productivity increases because you can reuse code.  Systems are easier to maintain and adapt to changing business needs.
  • 63.  Grouping related piece of information and processes into self-contained unit.  Makes it easy to change the way things work under the cover without changing the way users interact.  Hiding internal details.  Makes your object easy to use.
  • 64.  Protect access to the state of object.  It like fields, but they operate much like methods.  The get and set statements are called accessors. private double balance; public double Balance { get { return balance; } set { balance = value; } }
  • 65.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 66.  Inheritance specifies an is-a kind of relationship  Derived classes inherits properties and methods from base class, allowing code reuse  Derived classes become more specialized.
  • 67. public class Animal { public bool IsSleeping; public void Sleep() { Console.WriteLine("Sleeping"); } public void Eat() { } } public class Antelope : Animal { } public class Lion : Animal { public void StalkPrey() { } } public class Elephant : Animal { public int CarryCapacity; } Uses: Elephant e = new Elephant(); e.Sleep();
  • 68. public enum GenderType { Male, Female } public class Animal { public Animal() { Console.WriteLine("Constructing Animal"); } public Animal( GenderType gender ) { if ( gender == GenderType.Female ) { Console.WriteLine("Female "); } else { Console.WriteLine("Male "); } } } public class Elephant : Animal { public Elephant( GenderType gender ) : base( gender ) { Console.WriteLine("Elephant"); } } Elephant e = new Elephant(GenderType.Female); //Output: Female New line Elephant
  • 69.  You cannot derive from a sealed class  Prevents the class from being overridden or extended by third parties public sealed class Elephant { ... }
  • 70.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 71.  Polymorphism is an object-oriented concept that enables you to treat your derived classes in a similar manner, even though they are different.  When you create derived classes, you provide more specialized functionality; polymorphism enables you to treat these new objects in a general way.
  • 72.  A virtual method is one whose implementation can be replaced by a method in a derived class.  Use the keyword virtual, in the base class method  Use the override keyword, in the derived class method.  When you override a virtual method, the overriding method must have the same signature as the virtual method.
  • 73. public class Animal { public virtual void Eat() { Console.WriteLine("Eat something"); } } public class Cat : Animal { public override void Eat() { Console.WriteLine("Eat small animals"); } } public void FeedingTime( Animal someCreature ) { if ( someCreature.IsHungry ) { someCreature.Eat(); } } Cat myCat = new Cat(); FeedingTime(myCat);
  • 74.  The base keyword is used in derived classes to access members of the base class. public class Animal { public virtual void Eat() { Console.WriteLine("Eat something"); } } public class Cat : Animal { public void StalkPrey() { } public override void Eat() { base.Eat(); Console.WriteLine("Eat small animals"); } }
  • 75.  An abstract class is a generic base class  Contains an abstract method that must be implemented by a derived class.  An abstract method has no implementation in the base class  Can contain non abstract members  Any class that contains abstract members must be abstract
  • 76. public abstract class Animal { public abstract void Eat(); } public class Mouse : Animal { public override void Eat() { Console.WriteLine("Eat cheese"); } }
  • 77.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 78.  A data structure that contains a number of variables called element of the array.  All the array elements must be of the same type.  Arrays are zero indexed.  Arrays can be:  Single- dimentional, an array with the rank one.  Multidimentional, an array with the rank more than one  Jagged, an array whose elements are arrays
  • 79. Method Description Sort Sorts the elements in an array Clear Sets a range of elements to zero or null Clone Creates a copy of the array GetLength Returns the length of a given dimension IndexOf Returns the index of the first occurrence of a value Length Gets the number of elements in the specified dimension of the array
  • 80.  Declare the array by adding a set of square brackets to the end of the variable type of the individual elements int[] MyIntegerArray;  Instantiate to create int[] numbers = new int[5];  To create an array of type object object[] animals = new object[100];
  • 81.  Initialize an array int[ ] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; numbers[4] = 5;  Accessing array members string[] animals = {"Elephant", "Cat", "Mouse"}; Animals[1]= “cow”; String someAnimal = animals[2];
  • 82.  Using foreeach statement repeats the embedded statement(s) for each elements in the arrays. int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0}; foreach (int i in numbers) { Console.WriteLine(i); }
  • 83. using System; namespace ParameterExample { public class ParamExample { public int Sum(int[] list) { int total = 0; foreach ( int i in list ) { total += i; } return total; } } class Tester { static void Main(string[] args) { ParamExample pe = new ParamExample(); int[] tester = {1, 2, 3, 4, 5, 6, 7 }; int total = pe.Sum( tester ); Console.WriteLine( total ); // 28 } } }
  • 84.  params keyword used to pass a variable number of arguments to method class ParamExample { public string Combine(string s1, string s2, params object[] others) { string combination = s1 + " " + s2; foreach ( object o in others ) { combination += " " + o.ToString(); } return combination; } } You can use this method as follows: string combo = pe.Combine("One", "two", "three", "four" ); // combo has the value "One two three four" combo = pe.Combine("alpha", "beta"); // combo has the value "alpha beta"
  • 85.  When a class contains an array, or a collection, it is useful to access the information as though the class itself were an array.  An indexer is a property that allows you to index an object in the same way as an array.
  • 86. public class Zoo { private Animal[] theAnimals; public Animal this[int i] { get {return theAnimals[i];} set { theAnimals[i] = value;} } public Zoo() { theAnimals = new Animal[100]; } } public abstract class Animal { abstract public void Eat(); } public class Lion : Animal { public override void Eat() { } } public class Elephant : Animal { public override void Eat() { } } public class Antelope : Animal { public override void Eat() { } }
  • 87. class ZooKeeper { static void Main(string[] args) { Zoo myZoo = new Zoo(); myZoo[0] = new Elephant(); myZoo[1] = new Lion(); myZoo[2] = new Lion(); myZoo[3] = new Antelope(); Animal oneAnimal = myZoo[3]; } }
  • 88.  Lists, Queues, Statcks and Hash Tables are common way to manage data in an application  List: A collection that allows you access by index. Example: An array is a list, an ArrayList is a list  Queue: First in first out collection of objects. Example: Waiting in line at a ticket office.  Stack: Last in first out collection of objects. Example: a pile of plates  Hash Tables: Represents a collection of associated keys and values organized around the hash code of the key. Example: Dictionary
  • 89.  ArrayList does not have fixed size; it grows as needed  Use Add(object) to add an object to the end of the ArrayList  Use [] to access elements of the ArrayList.  Use TrimToSize() to reduce the size to fit the number of elements in the ArrayList  Use clear to remove all the elements  Can set the capacity explicitly
  • 90. public class Zoo { private ArrayList theAnimals; public ArrayList ZooAnimals { get {return theAnimals;} } public Animal this[int i] { get {return (Animal) theAnimals[i];} set {theAnimals[i] = value;} } public Zoo() { theAnimals = new ArrayList(); } }
  • 91. public abstract class Animal { abstract public void Eat(); } public class Lion : Animal { public override void Eat() { } } public class Elephant : Animal { public override void Eat() { } } public class Antelope : Animal { public override void Eat() { } }
  • 92. public class ZooKeeper { static void Main(string[] args) { Zoo myZoo = new Zoo(); myZoo.ZooAnimals.Add( new Lion() ); myZoo.ZooAnimals.Add( new Elephant() ); myZoo.ZooAnimals.Insert( 1, new Lion() ); Animal a = myZoo[0]; myZoo[1] = new Antelope(); } }
  • 93.  Queues: first in, first out  Enqueue places object in the Queue  Dequeue removes objects from the Queue.  Stacks: last in, first out  Push places object in the stack  Pop removes object from the stack  Counts get the number of objects contained in a stack or queue
  • 94. using System; using System.Collections; class Message { private string messageText; public Message (string s) { messageText = s; } public override string ToString() { return messageText; } } class Buffer { private Queue messageBuffer; public void SendMessage( Message m ) { messageBuffer.Enqueue( m ); } public void ReceiveMessage( ) { Message m = (Message) messageBuffer.Dequeue(); Console.WriteLine( m.ToString() ); } public Buffer() { messageBuffer = new Queue(); } }
  • 95. class Messenger { static void Main(string[] args) { Buffer buf = new Buffer(); buf.SendMessage( new Message("One") ); buf.SendMessage( new Message("Two") ); buf.ReceiveMessage (); buf.SendMessage( new Message("Three") ); buf.ReceiveMessage (); buf.SendMessage( new Message("Four") ); buf.ReceiveMessage (); buf.ReceiveMessage (); } } The preceding code produces the following output: One Two Three Four
  • 96. using System; using System.Collections; class Message { private string messageText; public Message (string s) { messageText = s; } public override string ToString() { return messageText; } } class Buffer { private Stack messageBuffer; public void SendMessage( Message m ) { messageBuffer.Push( m ); } public void ReceiveMessage( ) { Message m = (Message) messageBuffer.Pop(); Console.WriteLine( m.ToString() ); } public Buffer() { messageBuffer = new Stack(); } }
  • 97. class Messenger { static void Main(string[] args) { Buffer buf = new Buffer(); buf.SendMessage( new Message("One") ); buf.SendMessage( new Message("Two") ); buf.ReceiveMessage (); buf.SendMessage( new Message("Three") ); buf.ReceiveMessage (); buf.SendMessage( new Message("Four") ); buf.ReceiveMessage (); buf.ReceiveMessage (); } } The preceding code produces the following output: Two Three Four One
  • 98.  A hash table is a data structure that is designed for fast retrieval Book b2 = new Book("Inside C#", 0735612889 ); myReferences.bookList.Add(b2.ISBN, b2); Book b = (Book) myReferences.bookList[0735612889]; Console.WriteLine( b.Title );
  • 99.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 100.  Interface is a reference type that defines contact  Specifies the members that must be supplied by classes or interfaces that implement the interface  Can contain method, properties, indexers, event.  Does not provides implementation for the member  Can inherits zero or more members
  • 101. interface ICarnivore { bool IsHungry { get; } Animal Hunt(); void Eat(Animal victim); } public class Lion: ICarnivore { private bool hungry; public bool IsHungry { get { return hungry; } }
  • 102. interface ICarnivore { bool IsHungry { get; } Animal Hunt(); void Eat(Animal victim); } interface IHerbivore { bool IsHungry { get; } void GatherFood(); } interface IOmnivore: IHerbivore, ICarnivore { void DecideWhereToGoForDinner(); }
  • 103.  Abstract Class  Is a special kind of class that cannot be instantiated  An abstract class is only to be sub-classed(inherited from)  The advantage is that it enforces certain hierarchies for all the subclasses  It is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards  Interface  An interface is not a class  It is an entity that is defined by the word Interface  Interface has no implementation; it only has the signature  The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class  Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.
  • 104.  Introduction  C# Fundamentals  C# Pre defined Types  C# Expressions  Debugging Application  Conditional & Iteration Statement  Class, Method & Constructor  XML Comments  Static Class Member  Designing Object  Inheritance  Polymorphism  Arrays & Collections  Interface  Exception Handling
  • 105.  An exception is any error condition or unexpected behavior that is encountered by an executing program try { byte tickets = Convert.ToByte(numberOfTickets.Text); } catch (FormatException) { MessageBox.Show("Format Exception: please enter a number"); }
  • 106. try { byte tickets = Convert.ToByte(numberOfTickets.Text); } catch (FormatException e) { MessageBox.Show("Format Exception: please enter a number"); } catch (OverflowException e) { MessageBox.Show("Overflow: too many tickets"); }
  • 107.  A finally block is always executed, regardless of whether an exception is thrown. FileStream xmlFile = null; try { xmlFile = new FileStream("XmlFile.xml", FileMode.Open); } catch( System.IO.IOException e ) { return; } finally { if ( xmlFile != null ) { xmlFile.Close(); } }
  • 108.  You can create your own exception classes by deriving from the Application.Exception class class TicketException: ApplicationException { private bool purchasedCompleted = false; public bool PurchaseWasCompleted { get {return purchasedCompleted;} } public TicketException( bool completed, Exception e ) : base ("Ticket Purchase Error", e ){ purchasedCompleted = completed; } } The ReadData and run_Click methods can use TicketException: private int ReadData() { byte tickets = 0; try { tickets = Convert.ToByte(textBox1.Text); } catch ( Exception e ) { // check if purchase was complete throw ( new TicketException( true, e ) ); } return tickets; }
  • 109. private void run_Click(object sender, System.EventArgs ea) { int tickets = 0; try { tickets = ReadData(); } catch ( TicketException e ) { MessageBox.Show( e.Message ); MessageBox.Show( e.InnerException.Message ); } }