SlideShare una empresa de Scribd logo
1 de 114
Md. Mahedee Hasan
Senior Software Engineer
LEADS Corporation Limited
 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
 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
 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
 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
 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
 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*/
 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
 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
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
 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;
 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
 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;
 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
 Defining enumeration types
enum BluechipTeam{
Azad,
Mahedee,
Sarwar,
Jamil
}
 Using enumeration types
BluechipTeam aMember = BluechipTeam.Mahedee;
 Displaying the variables
Console.WriteLine(aMember);
 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
 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
 An expression is a sequence of operators and
operands
 The purpose of writing an expression is to
perform an action and return a value
 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
 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
 Setting break point
 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
 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
 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.
 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;
}
}
 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
}
 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.
 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 );
}
 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++);
}
 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);
}
 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 );
 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
 Classes
 Like blueprint of objects
 Contain methods and data
 Objects
 Are instances of class
 Create using the new keyword
 Have actions
 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
 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
 Boxing
 Treat value types like reference types
 Example: object boxedValue = (object) x;
 Unboxing
 Treat reference types like value types
 Example: int y = (int) boxedValue;
 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”;
 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
 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.
 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");
}
 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 );
 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
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;
}
}
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
}
}
 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";}
}
}
 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.
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 );
 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
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
 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.
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;
}
}
}
 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.
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();
 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
 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
 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.
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
 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
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() );
}
}
}
}
 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
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
 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.
 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.
 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;
}
}
 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
 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.
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();
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
 You cannot derive from a sealed class
 Prevents the class from being overridden or
extended by third parties
public sealed class Elephant {
...
}
 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
 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.
 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.
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);
 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");
}
}
 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
public abstract class Animal {
public abstract void Eat();
}
public class Mouse : Animal {
public override void Eat() {
Console.WriteLine("Eat cheese");
}
}
 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
 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
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
 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];
 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];
 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);
}
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
}
}
}
 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"
 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.
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() { }
}
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];
}
}
 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
 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
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();
}
}
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() { }
}
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();
}
}
 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
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();
}
}
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
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();
}
}
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
 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 );
 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
 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
interface ICarnivore {
bool IsHungry { get; }
Animal Hunt();
void Eat(Animal victim);
}
public class Lion: ICarnivore {
private bool hungry;
public bool IsHungry {
get {
return hungry;
}
}
interface ICarnivore {
bool IsHungry { get; }
Animal Hunt();
void Eat(Animal victim);
}
interface IHerbivore {
bool IsHungry { get; }
void GatherFood();
}
interface IOmnivore: IHerbivore, ICarnivore {
void DecideWhereToGoForDinner();
}
 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.
 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
 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");
}
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");
}
 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();
}
}
 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;
}
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 );
}
}
C# - Part 1

Más contenido relacionado

La actualidad más candente

Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 

La actualidad más candente (20)

C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 
C#.NET
C#.NETC#.NET
C#.NET
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
C# Tutorial
C# Tutorial C# Tutorial
C# Tutorial
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Learn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type ConversionLearn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type Conversion
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Abstract class
Abstract classAbstract class
Abstract class
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
C# programming language
C# programming languageC# programming language
C# programming language
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 

Destacado

C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3
Md. Mahedee Hasan
 
Visual programming lab
Visual programming labVisual programming lab
Visual programming lab
Soumya Behera
 
VC++ Fundamentals
VC++ FundamentalsVC++ Fundamentals
VC++ Fundamentals
ranigiyer
 

Destacado (20)

Oop principles
Oop principlesOop principles
Oop principles
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Introduction to TFS 2013
Introduction to TFS 2013Introduction to TFS 2013
Introduction to TFS 2013
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Add row in asp.net Gridview on button click using C# and vb.net
Add row in asp.net Gridview on button click using C# and vb.netAdd row in asp.net Gridview on button click using C# and vb.net
Add row in asp.net Gridview on button click using C# and vb.net
 
Feature and Future of ASP.NET
Feature and Future of ASP.NETFeature and Future of ASP.NET
Feature and Future of ASP.NET
 
C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3
 
The world of enterprise solution development with asp.net and C#
The world of enterprise solution development with asp.net and C#The world of enterprise solution development with asp.net and C#
The world of enterprise solution development with asp.net and C#
 
Introduction to OMNeT++
Introduction to OMNeT++Introduction to OMNeT++
Introduction to OMNeT++
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity Framework
 
Presentation1
Presentation1Presentation1
Presentation1
 
Visual programming lab
Visual programming labVisual programming lab
Visual programming lab
 
Window programming
Window programmingWindow programming
Window programming
 
VC++ Fundamentals
VC++ FundamentalsVC++ Fundamentals
VC++ Fundamentals
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Programming in c#
Programming in c#Programming in c#
Programming in c#
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Programming windows
Programming windowsProgramming windows
Programming windows
 

Similar a C# - Part 1

Similar a C# - Part 1 (20)

unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
 
VB Script Overview
VB Script OverviewVB Script Overview
VB Script Overview
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
c# at f#
c# at f#c# at f#
c# at f#
 
C# AND F#
C# AND F#C# AND F#
C# AND F#
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Chapter3: fundamental programming
Chapter3: fundamental programmingChapter3: fundamental programming
Chapter3: fundamental programming
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
IntroductionToCSharp.ppt
IntroductionToCSharp.pptIntroductionToCSharp.ppt
IntroductionToCSharp.ppt
 
Introduction toc sharp
Introduction toc sharpIntroduction toc sharp
Introduction toc sharp
 

Más de Md. Mahedee Hasan (9)

Azure Machine Learning
Azure Machine LearningAzure Machine Learning
Azure Machine Learning
 
Chatbot development with Microsoft Bot Framework and LUIS
Chatbot development with Microsoft Bot Framework and LUISChatbot development with Microsoft Bot Framework and LUIS
Chatbot development with Microsoft Bot Framework and LUIS
 
Chatbot development with Microsoft Bot Framework
Chatbot development with Microsoft Bot FrameworkChatbot development with Microsoft Bot Framework
Chatbot development with Microsoft Bot Framework
 
ASP.NET MVC Zero to Hero
ASP.NET MVC Zero to HeroASP.NET MVC Zero to Hero
ASP.NET MVC Zero to Hero
 
Introduction to Windows 10 IoT Core
Introduction to Windows 10 IoT CoreIntroduction to Windows 10 IoT Core
Introduction to Windows 10 IoT Core
 
Whats new in visual studio 2017
Whats new in visual studio 2017Whats new in visual studio 2017
Whats new in visual studio 2017
 
Increasing productivity using visual studio 2017
Increasing productivity using visual studio 2017Increasing productivity using visual studio 2017
Increasing productivity using visual studio 2017
 
Exciting features in visual studio 2017
Exciting features in visual studio 2017Exciting features in visual studio 2017
Exciting features in visual studio 2017
 
Generic Repository Pattern with ASP.NET MVC and EF
Generic Repository Pattern with ASP.NET MVC and EFGeneric Repository Pattern with ASP.NET MVC and EF
Generic Repository Pattern with ASP.NET MVC and EF
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

C# - Part 1

  • 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
  • 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.
  • 24.  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
  • 25.  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.
  • 26.  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; } }
  • 27.  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 }
  • 28.  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.
  • 29.  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 ); }
  • 30.  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++); }
  • 31.  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); }
  • 32.  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 );
  • 33.  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
  • 34.  Classes  Like blueprint of objects  Contain methods and data  Objects  Are instances of class  Create using the new keyword  Have actions
  • 35.  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
  • 36.  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
  • 37.  Boxing  Treat value types like reference types  Example: object boxedValue = (object) x;  Unboxing  Treat reference types like value types  Example: int y = (int) boxedValue;
  • 38.  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”;
  • 39.  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
  • 40.  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.
  • 41.  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"); }
  • 42.  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 );
  • 43.  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
  • 44. 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; } }
  • 45. 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 } }
  • 46.  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";} } }
  • 47.  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.
  • 48. 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 );
  • 49.  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
  • 50. 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
  • 51.  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.
  • 52. 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; } } }
  • 53.  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.
  • 54. 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();
  • 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.
  • 57.
  • 58.  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
  • 59.  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.
  • 60. 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
  • 61.  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
  • 62. 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() ); } } } }
  • 63.  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
  • 64. 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
  • 65.  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.
  • 66.  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.
  • 67.  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; } }
  • 68.  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
  • 69.  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.
  • 70. 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();
  • 71. 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
  • 72.  You cannot derive from a sealed class  Prevents the class from being overridden or extended by third parties public sealed class Elephant { ... }
  • 73.  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
  • 74.  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.
  • 75.
  • 76.  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.
  • 77. 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);
  • 78.  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"); } }
  • 79.  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
  • 80. public abstract class Animal { public abstract void Eat(); } public class Mouse : Animal { public override void Eat() { Console.WriteLine("Eat cheese"); } }
  • 81.  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
  • 82.  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
  • 83. 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
  • 84.  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];
  • 85.  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];
  • 86.  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); }
  • 87. 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 } } }
  • 88.  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"
  • 89.  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.
  • 90. 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() { } }
  • 91. 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]; } }
  • 92.  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
  • 93.  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
  • 94. 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(); } }
  • 95. 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() { } }
  • 96. 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(); } }
  • 97.  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
  • 98. 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(); } }
  • 99. 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
  • 100. 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(); } }
  • 101. 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
  • 102.  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 );
  • 103.  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
  • 104.  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
  • 105. interface ICarnivore { bool IsHungry { get; } Animal Hunt(); void Eat(Animal victim); } public class Lion: ICarnivore { private bool hungry; public bool IsHungry { get { return hungry; } }
  • 106. interface ICarnivore { bool IsHungry { get; } Animal Hunt(); void Eat(Animal victim); } interface IHerbivore { bool IsHungry { get; } void GatherFood(); } interface IOmnivore: IHerbivore, ICarnivore { void DecideWhereToGoForDinner(); }
  • 107.  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.
  • 108.  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
  • 109.  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"); }
  • 110. 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"); }
  • 111.  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(); } }
  • 112.  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; }
  • 113. 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 ); } }

Notas del editor

  1. 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 = &quot;This is a literal&quot;; 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 &apos;M&apos; in 10000000M means this is a decimal value, rather than int or double. varaccountBalance = 10000000M;
  2. C# has four types of operators: unary, binary, ternary, and afew others that don’t fit into a category.
  3. 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.
  4. Difference between readonly and constant.
  5. 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&apos;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-&gt;another difference between array list and array is arraylist can dynamically increase or decrease its size were as array size is constant