Session 3 CSharp ExceptionHandling Struct Class

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 98

IMCEITS

Session 3

Exception Handling, Enumerations, Structs, Class

1
IMCEITS
Contents
 Error Handling (Exception Handling)
 Enumeration
 Structs
 Classes
 Constructors & Destructor
 Static & Instance Member
 Properties &Indexers
 Overloading

2
IMCEITS

Error Handling
(Exception Handling)

3
IMCEITS

Errors
 Mistakes that can make a program go wrong
 May produce an incorrect output or may terminate the
execution of the program abruptly or even may cause
the system to crash.
 2 categories in error : Compile time errors and
Run-time errors

4
IMCEITS

Exception
 A condition that is caused by a run-time error in the
program
 When an error occurs, it creates an exception object
and throws it (i.e., inform that an error has occurred.

5
IMCEITS

Exception Handling
 To handle any possible errors that may occur at run
time C# support the mechanism known as
exception handling.
 Exception is an object created (or throw) when a
particular exceptional error condition occurs.
 .NET provides many predefine exception classes
which are in .NET Base Class Library.
 Programmer can create own exception class.
 The CLR defines how exceptions are thrown and
how they’re handled.

6
IMCEITS

Exception Handling (Cont.)


 Mechanism – 4 steps
 Find the problem ( Hit the exception )
 Inform that an error has occurred ( Throw the
exception )
 Receive the error information ( Catch the
exception )
 Take corrective actions ( Handle the exception )

7
IMCEITS
Object

Exception Classes Exception

SystemException ApplicationException

Derive your own


ArgumentException exception classes from
this ApplicationException

ArgumentNullException IOException

ArgumentOutOfRangeException FileLoadException

UnauthorizedAccessException
FileNotFoundException
StackOverflowException

ArithmticException DirectoryNotFoundException

OverflowException EndOfStreamException
8
IMCEITS

Exception Handling (Cont.)


 System.Exception is derived from System.Object
 System.Exception has two important classes
 System.SystemException
 Might be thrown by almost any application
 ArgumentException, StackOverflowException,IOException,
ArithmeticException, …
 System.ApplicationException
 Define by third parties.
 You can throw an exception in any language and
catch it in any other.
 CLR’s Exception Handling Mechanism:
 try, catch, finally, and throw
9
IMCEITS

The C# Syntax
try {
// block of code to monitor for errors
}catch (ExcepType1 exObj) {
//error handling for ExcepType1
}catch ExcepType2 exObj){
//error handling for ExcepType2
}

 ExcepType is the type of error that has occurred


 exObj is optional ( If the exception handler does not need access to the
exception object, there is no need to specify exObj.)

10
IMCEITS

The C# Syntax (Cont.)


• try {
//code for normal execution
}catch (FileNotFoundException e) {
//error handling – System.Exception object (trap very specific error)
}catch (Exception ex){
//error handling – System.Exception object (cover any error)
}catch {
//error handling , written in other languages
//.NET exception object (no idea what class exception)
}finally {
// Always come here even if there were exceptions.
//clean up resources
}
• throw new FileNotFoundException();

11
IMCEITS

Some variations
 catch clauses are checked in sequential order.
 catch only exception you can handle and recover from
 more than one catch block to handle specific types of errors
 Exception parameter name can be omitted in a catch clause.
 Exception type must be derived from System.Exception. If
exception parameter is missing, System.Exception is assumed.
 finally block is optional
 finally block is always executed (if present).
 Define your own exception types for clarity
 Protect resource handlers with finally
 thrown statement inside the try block

12
IMCEITS

System.Exception
 Properties
 e.Message the error message as a string;
 set in new Exception (msg);
 e.StackTrace trace of the method call stack as a string
 e.Source the application or object that threw the
exception
 e.TargetSite the method object that threw the exception
 ...
 Methods
 e.ToString() returns the name of the exception

13
IMCEITS

Exception Handling
 Contains information about exception location
 Contains a stack trace
 Contains a message
 Can contain an inner exception
 Can contain custom information

14
IMCEITS

Throwing an Exception
 By an invalid operation (implicit exception)
 Division by 0
 Index overflow
 Access via a null reference...
 By a throw statement (explicit exception)
throw new FunnyException(10);
class FunnyException : ApplicationException{
public int errorCode;
public FunnyException(int x) { errorCode = x; }
}
15
IMCEITS

try…catch : Example-1
using System;
class ExceptionDemo1{
static void Main(string[] args)
{
int[] nums = new int[4];
try
{    Output
Console.WriteLine("Before exception is generated."); Before exception is generated.
for (int i = 0; i < 10; i++)
{ nums[i] = i; nums[0]: 0
Console.WriteLine("nums[{0}]:{1}", i, nums[i]); nums[1]: 1
}
nums[2]: 2
Console.WriteLine("This is won't be displayed.");
} catch(IndexOutOfRangeException ){ nums[3]: 3
Console .WriteLine ("Index out-of-bound!"); Index out-of-bound!
}//catch
Console.WriteLine("After catch statement."); After catch statement.
}} 16
IMCEITS

try…catch : Example-2
class ExceptionDemo2
{
public static void genException()
{
int[] nums = new int[4];
Console.WriteLine("Before exception is generated.");
for (int i = 0; i < 10; i++) - Inside genException, an
{ IndexOutOfRangeException is generated.
nums[i] = i; -Not caught by genException()
Console.WriteLine("nums[{0}]:{1}", i, nums[i]);
}
Console.WriteLine("This is won't be displayed.");

}
static void Main(string[] args) - Exception is caught by the catch
{ statement associated with catch in Main
try{
genException();
}catch (IndexOutOfRangeException )
{
Console.WriteLine("Index out-of-bound!"); Output
}//catch Same with Demo1
Console.WriteLine("After catch statement.");
17
} }
IMCEITS

try…catch : Example-3
using System;
class ExceptionDemo3{    Output
static void Main(string[] args) Before exception is generated.
{
nums[0]: 0
int[] nums = new int[4];
nums[1]: 1
try
{ nums[2]: 2
Console.WriteLine("Before exception is generated."); nums[3]: 3
for (int i = 0; i < 10; i++)
Unhandled Exception :
{ nums[i] = i;
Console.WriteLine("nums[{0}]:{1}", i, nums[i]); System.IndexOutOfRangeException:
}
- DivideByZeroException won’t
Console.WriteLine("This is won't be displayed.");
catch
} catch(DivideByZeroException ){ IndexOutOfRangeException
Console .WriteLine ("Index out-of-bound!"); -catch(Exception) handles all
}//catch types of error
- catch all exceptions, no matter
Console.WriteLine("After catch statement.");
the type
}} 18
-catch{ }
IMCEITS

Multiple try…catch : Example-4


class ExceptionDemo4
{
public static void Main()
{
int[] number = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom={2,0,4,4,0,8}; Output
for(int i=0;i<number.Length ;i++)
{ 4 / 2 is 2
try Can’t divide by zero.
{
Console.WriteLine(number[i] + " / " + denom[i] + 16 / 4 is 4
" is " + number[i] / denom[i]);
} 32 / 4 is 8
catch (DivideByZeroException)
{ Can’t divide by zero.
Console.WriteLine("Can't divide by zero."); 128 / 8 is 16
}catch(IndexOutOfRangeException ){
Console.WriteLine("No matching element found"); No matching element found
}
}//for No matching element found
} } 19
IMCEITS
Nested try blocks
try{ • an exception is
//point A
try{ • thrown inside outer try
//point B
}catch{
block(point A, D) – same
//point C • inner try point B – if handle
}finally{
// clean up
suitable catch and then execute
} inner finally block. No code
//point D execute outside any finally block.
}catch{
//error handling • If not, finally block is executed
}finally{ and look outer catch. If handle
//clean up
}
suitable catch or not ,executed
outer finally block.
20
IMCEITS

Nested try…catch : Example-5


class ExceptionDemo5 finally {
{ Console.WriteLine("Inner finally");
public static void Main() }// inner finally
{ }//for
int[] number = { 4, 8, 16, 32, 64, 128, 256, }//outer try
512 }; catch (IndexOutOfRangeException)
int[] denom = { 2, 0, 4, 4, 0, 8 }; {
try{//outer try Console.WriteLine("No matching
for (int i = 0; i < number.Length; i++) element found");
{ }// outer catch
try finally {Console .WriteLine ("Outer
{// inner try finally");}
Console.WriteLine(number[i] + " / " + }//main
denom[i] + " is " + number[i] / }
denom[i]);
} catch (DivideByZeroException)
{ Console.WriteLine("Can't divide by
zero.");
}
21
IMCEITS

Nested try…catch : Example-5


Output Inner finally.
4 / 2 is 2 Inner finally.
Inner finally. No matching element found
Can’t divide by zero. Outer finally.
Inner finally.
16 / 4 is 4
Inner finally.
32 / 4 is 8
Inner finally.
Can’t divide by zero.
Inner finally.
128 / 8 is 16
22
IMCEITS

Throwing an Exception: Example-6


class ExceptionDemo6
{
public static void Main()
{
Output
try
{ Before throw.
Console.WriteLine("Before throw."); Exception caught.
throw new DivideByZeroException(); After try,catch block.
}
catch (DivideByZeroException)
{
Console.WriteLine("Exception caught.");
} finally {
Console.WriteLine("After try,catch block."); }
} }
23
IMCEITS
User Define Execption : Example 7
public class CountIsZeroException: ApplicationException
{
public CountIsZeroException()    {    }
public CountIsZeroException(string message): base(message) {    }
public CountIsZeroException(string message, Exception inner) 
   : base(message, inner)    {    }
}// class CountIsZeroException

- Create CountIsZeroException
which is derived from
ApplicationException
- Define 3 Constructors
24
IMCEITS
User Define Execption : Example 7
public class Summer{
int    sum = 0;
int    count = 0;
float    average;
public void DoAverage()    
{
    if (count == 0)
    throw(new CountIsZeroException("Zero count in DoAverage"));
    else
    average = sum / count;
 }// DoAverage method
}// class Summer

- Create Summer
- Define DoAverage() function
which throws User Defined
Exception
(CountIsZeroException object) 25
IMCEITS
User Define Execption : Example 7
using System;
public class UserDefinedExceptionClasses
{
public static void Main()    
{
Summer summer = new Summer();
try {
       summer.DoAverage();
   }catch (CountIsZeroException e)        {
   Console.WriteLine("CountIsZeroException: {0}", e);
   }}}
26
IMCEITS
User Define Execption : Example 7
Output
CountIsZeroException:Session3.CountIsZeroException: Zero count in
DoAverage at Session3.Summer.DoAverage() in
C:\C#_Batch4_Program\Session3\UserDefinedExceptionClasses.cs:line 29
At Session3. UserDefinedExceptionClasses.Main() in
C:\C#_Batch4_Program\Session3\UserDefinedExceptionClasses.cs:line 12

27
IMCEITS

Enumeration

28
IMCEITS
Enumeration

 a set of named integer constants


 implicitly derives from System.Enum
 Enumerate type : enum (keyword)
 General form:
 enum name{enumeration list};

29
IMCEITS
Enumeration

 enum Color {Red,Green,Blue};


 Color.Red // Red
 Color.Green // Green
 Color.Blue // Blue
 Color mycolor;
 mycolor = Color.Green;
 Console.WriteLine(mycolor); // Green
 Console.WriteLine((int)mycolor); // 1

30
IMCEITS
Enumeration
 General form
 enum Color {Red,Green,Blue};
 By default, it starts with 0; can be changed to any number.
 enum Color{Red = 10, Green, Blue}
 By default, it increments by 1 for each subsequent name.
 You can sign a value to each name.
 enum Color{ Red = 10, Green = 20, Blue = 21}
 You can increment a enum variable.
 Color mycolor;
 mycolor = Color.Green;
 mycolor += 1;
 Console.WriteLine(mycolor); // Blue
 Integer casting must be explicit
 Color background = (Color)2;
 int oldColor = (int)background;
31
IMCEITS
Enumeration
 Strongly typed
 No implicit conversions to/from int
 Operators: +, -, ++, --, &, |, ^, ~
 Can specify underlying type
 Byte, short, int, long
 enum Color: byte
 {
 Red = 1,
 Green = 2,
 Blue = 4,
 Black = 0,
 White = Red | Green | Blue,
 }
 Color secondColor = (Color)Enum.Parse(typeof(Color), "GREEN", true );
 // true – ignore case

32
IMCEITS
Operations on Enumerations
 Compare
– if (c == Color.red) ...if (c > Color.red && c <= Color.green) ...
 +, -
– c = c + 2;
 ++, --
– c++;
 &
– if ((c & Color.red) == 0) ...
 |
– c = c | Color.blue;
 ~
– c = ~ Color.red;

33
IMCEITS

Enumeration : Example
using System;
class EnumDemo {
enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland,McIntosh};
static void Main()
{
string[] color = { "Red", "Yellow“, "Red", "Red", "Red", "Reddish Green“ };
Apple i; // declare an enum variable
// Use i to cycle through the enum.
for(i = Apple.Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine(i + " has value of " + (int)i);
Console.WriteLine();
// Use an enumeration to index an array.
for(i = Apple.Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine("Color of " + i + " is " + color[(int)i]);
34
}}
IMCEITS

Enumeration : Example
Output
Jonathan has value of 0
GoldenDel has value of 1
RedDel has value of 2
Winesap has value of 3
Cortland has value of 4
McIntosh has value of 5

Color of Jonathan is Red


Color of GoldenDel is Yellow
Color of RedDel is Red
Color of Winesap is Red
Color of Cortland is Red
35
Color of McIntosh is Reddish Green
IMCEITS

Structures

36
IMCEITS
Structs

 What is structure?
 Defining & Declaration
 Assigning Values to Members
 Copying Structs
 Structs with Methods
 Property
 Nested Structs
 Structure Array

37
IMCEITS
Structures
 Structs
 Value types, Assignment copies data, not reference
 Stack based elements, stored in-line, not heap allocated
– More efficient use of memory
– auto destruction, no garbage collection
– less overhead, code runs faster
– less flexible, sizes need to be known at compile time
 Always inherit directly from System.Object
 Similar to a class but no inheritance, virtual ,protected and
abstract methods
 it is not possible to inherit from a struct, nor can a struct inherit
from another struct or class
 Can implement one or more interfaces

38
IMCEITS
Structs
 Includes methods, fields, indexers, properties,
operator methods, and events
 Can define constructor but not destructor and
default constructor.
 The default (no-parameter) constructor of a struct is
always supplied by the compiler and cannot be
replaced
 Can use new operator :
– if use specified constructor is called.
– If not the object is still created, but it is not initialized.

39
IMCEITS
Structs : Defining & Declaration

struct struct_name{ struct Student{


data_type member1; public string name;
public int rollno;
data_type member2;
public double total_mark;
} }

struct_name stvar; Student s1;

40
IMCEITS
Structs : Assigning Values to Members

struct Student{
public string name;
public int rollno;
public double total_mark;
}
Student s1;
s1.name= “Bo Bo”;
s1.rollno = 1;
s1.total_mark = 580.5;

41
IMCEITS
Structs : Copying Structs

struct Student{
public string name; private by default
public int rollno;
public double total_mark;
}
Student s1,s2;
s1.name= “Bo Bo”;
s1.rollno = 1;
s1.total_mark = 580.5;
s2 = s1;

42
IMCEITS
Structs : Structs with Methods

struct Number{
int num;
public Number(int value) // constructor
{
number = value;
}
Number n1=new Number(100); // initialization

43
IMCEITS

Struct: Example-1
struct Student Student st = new Student("Ma Ma", 1,
{ 570.5);
public string name; Console.WriteLine("Name :{0}\nRoll no :
public int rno; {1}\nTotal :{2}", st.name, st.rno,
public double total; st.total);
public Student(string na,int r,double t) }}
{
name = na;
rno = r; Output
total = t;
} Name : Ma Ma
}
class Struct_Constructor Roll no : 1
{
public static void Main()
Total : 570.5
{ 44
IMCEITS

Struct: Example-2
struct Student public double Total
{ {
string name; get { return total ; }
int rno; set { total = value; }
double total; }
public string Name }
{ class Struct_Property
get { return name; } {
set { name = value; } public static void Main()
} {
public int Rno Student st2=new Student();
{ st2.Name = "Kyaw Kyaw";
get { return rno; }
st2.Rno = 3;
set { rno = value; }
st2.Total = 581.5;
}
Console.WriteLine("Name :{0}\nAge :
{1}\nTotal :{2}", st2.Name ,st2.Rno
,st2.Total ); 45
IMCEITS

Structs : Example 3
struct Point{ Console.WriteLine
public int x; ("p1 = ({0}, {1})", p1.x, p1.y);
public int y; // Writes "(1, 2)"
} Console.WriteLine
//Creates a value object on stack. ("p2 = ({0}, {1})", p2.x, p2.y);
Point p1 = new Point(); // Writes "(3, 4)“
p1.x = 1; //Creates a value object on the stack
p1.y = 2; Point p3;
//Makes a new copy of the object p3.x = 5; // It works.
on the stack p3.y = 6;
Point p2 = p1; Console.WriteLine
p2.x = 3; ("p3 = ({0}, {1})", p3.x, p3.y);
p2.y = 4; // Writes "(5, 6)"

46
IMCEITS

Structs : Nested Structs


struct struct1_name{ struct Date{
data_type member1; public int day,month,
year;
data_type member2; }
} struct Student{
struct struct2_name{ public string name;
struct1_name member1; public int rollno;
data_type member2; public double total_mark;
public Date d1;
}
}
struct2_name stvar; 47
IMCEITS

Structs : Nested Structs


Student s1=new Student();
s1.d1.day=5;
s1.d1.month=10;
s1.d1.year=2009;

48
IMCEITS

Struct: Example-4
struct Date class Nested_Struct
{ {
public int day, month, year; public static void Main()
} {
struct Student Student st = new Student("Ma Ma", 1,
{ 570.5,5,11,1983);
public string name; Console.WriteLine("Name :{0}\nAge :
public int rno; {1}\nTotal :{2}\nDate of birth :{3} : {4}:{5}",
public double total; st.name, st.rno, st.total, st.dob.day,
st.dob.month, st.dob.year);
public Date dob;
public Student(string na,int r,double t,int
dd,int mm,int yy) Output
{ name = na;
Name : Ma Ma
rno = r;
total = t; Roll no : 1
dob.day = dd;
dob.month = mm;
Total : 570.5
dob.year = yy; }} Date of birth : 5:11:1983 49
IMCEITS

Structs : Structs Array


struct Student{
public string name;
public int rollno;
public double total_mark;
}

Student[] stArr=new Student[5];


stArr[0].name=“Ma Ma”;
stArr[0].rollno= 1;
stArr[0].total_mark= 550.6;
stArr[1].name=“Bo Bo”;
stArr[1].rollno= 2;
stArr[1].total_mark= 555.6;
50
IMCEITS

Classes And Structs


class CPoint { int x, y; ... }
struct SPoint { int x, y; ... }

CPoint cp = new CPoint(10, 20);


SPoint sp = new SPoint(10, 20);

10
sp
20

cp CPoint
10
20

51
IMCEITS

Classes

52
IMCEITS

Classes
What is Class?
Member Access
Object
Methods & Parameters
Nested Classes
Constructor & Destructor
Instance and Static Member
Differences between Structs and Classes
Properties & Indexers
Overloading
53
IMCEITS
Classes
 Is a template that defines the form of an object.
 Is a logical abstraction.
 Specifies both the data and code that will operate on that
data.
 used to construct an object.
 Objects are instances of a class.
 is reference type, stored in the heap.
 Class members
– Data members
– Function members
– Nested type

54
IMCEITS
Classes
Data members
 Contains the data for the class – fields, constants and
events
 Either static or instance variable
 Fields
– Variables associate with the class
 Constants
– The same way as variable
– Keyword : const
 Events
– A field or property of the class changing, or some form of
user interaction occurring.
55
IMCEITS
Classes
Function members
 Provide some functionality for manipulating the data
in the class
 Include methods, constructors, (finalizer) destructors,
indexers, operators, and properties.
Keyword
 To create a class : class
 To declare instance : new
Member access
 public, protected, internal, private
56
IMCEITS
Classes
Member access
 Public, protected, internal, private
Form Meaning

public Access not limited.

Protected Access limited to the containing class or types derived from


the containing class.

internal Access limited to this program.

protected internal Access limited to this program or types derived from the
containing class.

private Access limited to the containing type.

57
IMCEITS
Example of a Class
class MyClass public void MyMethod()
{ { Console.WriteLine("MyClas
s.MyMethod");
public const int MyConst = 12;
}
public int MyField;
public int MyProperty {

get {
public MyClass() {
return MyField;
MyField=0;
}
Console.WriteLine("Instance
constructor"); set {
} MyField = value;
public MyClass(int value) { }
MyField = value; }
Console.WriteLine("Instance …
constructor");
} …
~MyClass() { }
Console.WriteLine("Destructor");
} 58
IMCEITS
Objects
 New operator
– Dynamically allocates memory for an object and returns a
reference to it. (this reference is then stored in a variable)
 All class objects must be dynamically allocated
 Syntax
– Class obj=new Class();
– Class obj;//declare reference to object
– obj=new Class();//allocate a Class object
 Using new with Value type
– int i=new int(); //initialize i to zero
– int i; //uninitialize
– Console.WriteLine(i); // ??????

59
IMCEITS

Reference Variable and Assignment


 MyClass obj1=new MyClass();
 MyClass obj2=obj1;
 obj1.MyField=34; Console.WriteLine(obj2.MyField);
 MyClass obj3=new MyClass();
 obj2=obj3;
 Console.WriteLine(obj2.MyField);//?????????

60
IMCEITS
Methods
 Declaring
[modifier] return_type Methodname ([parameter]) {
// method body
}
public bool IsPoistive(int val)
{
if (val>0) return true;
return false;
}
 Invoking
MethTest mth=new MethTest();
If( mth.IsPositive(10)) Console.WriteLine(“----”);

61
IMCEITS
Methods
 Passing parameters

– To pass one or more values /references

 Pass references

public bool sameAs(MyClass obj){


//method body
}

62
IMCEITS

Methods
• Using ref Parameters

public void Sqr(ref int i)


{
i=i*i;
}
int a=10;
obj.Sqr(ref a);

63
IMCEITS

Methods
• Using out Parameters

public void Function(out int i){


i=100;
}
int k;
obj.Function(out k);
Console.WriteLine(k);//?????

64
IMCEITS

Methods
•Using a variable Number of Arguments
public int MinVal (params int[] nums){
int m;
if(nums.Length = = 0) {
Console.WriteLine(“Error: no arguments.”)
return 0; }
m = nums [0];
for (int i =1;i< nums.Lenght;i++)
if (nums [i] < m) m= nums[i];
return m;
}
65
IMCEITS

Methods
int i=obj.MinVal(10,20,30);
int i=obj.MinVal(10);
int i=obj.MinVal();
int[] arg={10,20,30};
int i=obj.MinVal(arg);

66
IMCEITS

Methods
• Passing Arguments to Main( )
static void Main( string[] args )
static int Main ( string[] args )

class CLDemo{
public static void Main ( string[] args ) {
Console. WriteLine (“ There are “ + args.Length + “
command-line arguments : \n”);
for ( int i=0; i<args.Length ; i++)
Console.WriteLine (args [i]);
}
}
67
IMCEITS

Methods
• Returning Objects
class Rect{
int width;
int height;
public Rect(int w,int h) { width = w; height = h; }
public Rect enlarge (int factor)
{ return new Rect (width * factor, height * factor);}
}
Rect r1= new Rect( 4,5);
Rect r2= r1. enlarge(3);

68
IMCEITS

Methods
• Returning An Array
public int [] find_factors (int num, out int numfactors )
{ int[] facts = new int[80];
int i, j;
for (i =2; j =0; i<num /2 +1 ;i++)
{ if (num%i ) = = 0){
facts [j] = i;
j ++; }
}
numfactors = j;
return facts;
}
69
IMCEITS

Methods
• Recursive method
public int fact (int n)
{
if ( n = = 1)
return 1;
result = fact (n-1) * n;
return result;
}

70
IMCEITS

Methods
int numfactors;
int[] factors;
factors = find_factors ( 100, out numfactors);
Console.WriteLine (“ Factors for 100 are : “);
for ( int i=0 ; i< numfactors; i++)
Console.WriteLine (factors[i] + “ “);

OUTPUT
Factors for 100 are :
2 4 5 10 20 25 50
71
IMCEITS

Nested Types
class A {
int x; class NestedClass
public class B { {
int x;
static public void Main()
{
public B() { } A a = new A();
public B(A obj) { A.B b = new A.B(a);
x = obj.x;
} }
public void f(){ }
}
}
public void fun() {
B b = new B();
b.f();
}
72
}
IMCEITS
Nested Types
• For auxiliary classes that should be hidden
- Inner class can access all members of the outer class (even
private members).
- Outer class can access only public members of the inner
class.
- Other classes can access an inner class only if it is public.
• Nested types can also be structs, enums, interfaces and delegates.

73
IMCEITS
Constructors & Destructors
Constructors
 Same name as its class
 syntactically similar to a method
 have no return type
 Initializes an object when it is created
 Usually access is public
 Automatically default constructor is provided if no constructors
define
 Once define a constructor, default constructor is no longer used.
 Constructor is called by new when object is created
Destructors (Finalize method)
 Declare like a constructor except that it is preceded with a ~ (tilde).
 No return type
 The order and timing of destruction is undefined
 cannot rely on timing and thread ID
74
IMCEITS
Constructors
Syntax:
 General form
access class-name(){//constructor code}
 Parameterized constructor
access class-name([parameters]){//constructor code}
 Overload constructor
– To allow one object to initallized another
public Stack(Stack obj){//constructor code}
Stack stk1=new Stack();
Stack stk2=new Stack(stk1);//stk2=stk1;
75
IMCEITS
Constructors
Syntax:
 Invoking an overloaded constructor through this
– constructor-name(parameter-list1):this(parameter-
list2){//constructor body}
– class XYCoord{
int x,y;
public XYCoord():this(0,0){}
public XYCoord(XYCoord obj):this(obj.x,obj.y){}
public XYCoord(int i,int j){x=i; y=j;}
}

76
IMCEITS
Instance and Static Member
Instance Member
 general form for declaration for instance variables
– Access type var-name;
– public int i;
Static Member
 It can be accessed before any objects of its class are
created
 without any reference to objects
 Can declare both methods and variables

77
IMCEITS
Static Member
 Cannot be accessed through an object reference
 Can be call by use dot operator on the name of the
class
 Is global variable
 All instances of the class share the same static
variable
 Is initialized when its class is load if no explicit
initilizer is specified.
 Always has a value

78
IMCEITS
Static Member (Cont.)

Restrictions that apply to static methods


 Does not have this reference
 Can directly call only other static methods (not call
an instance methods of its class)
 Must directly access only static data (not directly
use an instance variable)

79
IMCEITS
Static
Static constructors
 is called automatically and before the instance constructor
 cannot have access modifier(use default access & can’t be call
by other program)
class Cons{ class Demo{
public static void Main()
public static int alpha; {
public int beta; Cons cn=new Cons();
Console.WriteLine
static Cons(){alpha=90;} (“alpha=”+cn.alpha);//90
Console.WriteLine
public Cons(){ beta=100;} (“beta=”+cn.beta);//100
} }
}
80
IMCEITS
Static Class
 Static Class
 Two key features
1. No object of a static class can be created
2. Contains only static members
 Benefits
– the compiler to prevent any instances of that class
from being created
 Notes:
– all members must be explicitly specified as static.(not
automatically make static members)
– can not have instance constructor.
– can have a static constructor.
81
IMCEITS
Differences between Class and Struct

Classes Structs
 Reference Types • Value Types
 (objects stored on the • (objects stored on the stack)
heap) • no inheritance
 support inheritance • (but compatible with
 (all classes are derived object)
from object) • can implement interfaces
 can implement interfaces • no destructors allowed
 may have a destructor

82
IMCEITS

Properties and Indexer

83
IMCEITS
Properties

 Smart fields
 The use of private variable along with methods to
access its value
 Can be used in expressions and assignments like a
normal variable
 Do not define storage locations
 Manages access to a field
 Usually specified as public

84
IMCEITS
Properties
Syntax: class Demo{
type name{ public static void Main(){
get{return type;} //get accessor SimProp p=new SimProp();
set{var=value;} //set accessor p.Prop=10;
} Console.WriteLine(p.Prop);
----------------------------------------- }
class SimProp{ }
int _prop;
public int Prop{
get{return _prop;} class SimProp{
set{_prop=value;} int _prop;
} int Prop{
get{return _prop;}
} private set{_prop=value;}
}
}
85
IMCEITS
Properties
Restrictions
 cannot be passed as a ref or out parameter to a method.
(bcoz: not define a storage locations)
 can‘t overload
 should not alter the state of the underlying variable when the
get accessor is called.
 using access modifiers with accessors
– only the set or get accessor can be modified, not both
– the access modifier must be more restrictive than the access level
of the property or indexer.
– access modifier can’t be used when declaring an accessor within
an interface or implementing an accessor specified by an
interface.

86
IMCEITS
Indexers
 Smart arrays
 allows an object to be indexed like an array
 can have one or more dimensions
 two accessor: get and set
– similar to a method except that does not have a return type or parameter
declarations
 Accessors are automatically called when the indexer is used
 can create read only or write only
 can be overload
 not required an underlying array.
Notes:
 does not define storage locations(i.e. cannot be passed as a ref or out
parameter to a method.)
 must be instance member of its class.(so, can’t be declared as static)

87
IMCEITS
Indexers (Cont.)

 General form
element-type this[int index]{
//get accessor
get{//return the value specified by index}
//set accessor
set{//set the value specified by index}
}

88
IMCEITS
Indexer : Example
using System; static void Main(string[] args)
class IntIndexer { int size = 10;
{ private string[] myData;         IntIndexer myInd = new
public IntIndexer(int size) IntIndexer(size);
{   myData = new string[size];         myInd[9] = “Some Value”;
for (int i=0; i < size; i++)         myInd[3] = “Another Value”;
{ myData[i] = "empty";    }            myInd[5] = “Any Value”;
}         Console.WriteLine("\nIndexer
Output\n");
  public string this[int pos]
        for (int i=0; i < size; i++)
{ get {
{ return myData[pos];    }     Console.WriteLine("myInd[{0}]:
    set {1}", i, myInd[i]);
 }
{ myData[pos] = value;}
}
}
} 89
IMCEITS

Indexer : Example
Output
myInd[0]: empty
myInd[1]: empty
myInd[2]: empty
myInd[3]: Another Value
myInd[4]: empty
myInd[5]: Any Value
myInd[6]: empty
myInd[7]: empty
myInd[8]: empty
myInd[9]: Some Value 90
IMCEITS

Indexers (Example)
class Student {
private int[] marks = new int[10];
public int this[int i] {
get { return marks[i]; }
set { marks[i] = value; }
}}

class Program {
static void Main(string[] args) {
Student s1= new Student();
s1[0] =75;
System.Console.WriteLine(“Mark for Subject1: ”+s1[0]);
}
} 91
IMCEITS

Operator Overloading

92
IMCEITS
Operator Overloading

 Two forms of operator methods:


– unary operators
– binary operators
 General form for unary operator
public static ret-type operator op(prarm-type perand)
{//oprations}
 General form for binary operator
public static ret-type operator op(prarm-type1 operand1,
prarm-type2 operand2){ //oprations}

93
IMCEITS
Operator Overloading

public static Time operator+(Time t1, Time t2){


int newHours = t1.hours + t2.hours;
int newMinutes = t1.minutes + t2.minutes;
return new Time(newHours, newMinutes);
}

94
IMCEITS
Operator Overloading
Overloadable operators:
 +-*/%
 ++ -- (both postfix and prefix)
 == != < > <= >=
 &|~^!
 true false

95
IMCEITS
Operators Restrictions
 = cannot be overloaded
 && and || cannot be overloaded directly
– are evaluated using &, |, true, false
 *=, /=, +=, -=, %= cannot be overloaded
– are evaluated using *, /, +, -, % operators
 &=, |=, ^=, >>=, <<= cannot be overloaded
 Relational operators must be paired (< and >, <= and
 >=, == and !=)
 Override the Equals method if overloading == and !=
 Override the GetHashCode method if overriding Equals
method

96
IMCEITS
Conversion Operators
 public static explicit operator Time (float hours){ ... }
 public static explicit operator float (Time t1){ ... }
 public static implicit operator string (Time t1){ ... }
 Time t;
 string s = t;
 float f = (float)t;
 If a class defines a string conversion operator, it should override
ToString

97
IMCEITS

98

You might also like