11-06-25-11-23-51-966-carun

download 11-06-25-11-23-51-966-carun

of 67

Transcript of 11-06-25-11-23-51-966-carun

  • 8/10/2019 11-06-25-11-23-51-966-carun

    1/67

    UNIT II OBJECT ORIENTED ASPECTS OF C#

    Syllabus:

    Classes, Objects, Inheritance, Polymorphism, Interfaces, Operator Overloading, Delegates, Events,

    Errors and Exceptions.

    Introducing Classes and Objects

    The class is the foundation of C# because it defines the nature of an object. Furthermore, the

    class forms the basis for object-oriented programming. Within a class are defined both code and data.

    Because classes and objects are fundamental to C#, they constitute a large topic, which spans several

    chapters. This chapter begins the discussion by covering their main features.

    Class Fundamentals

    Since all C# program activity occurs within a class, we have been using classes since the startof this book. Of course, only extremely simple classes have been used, and we have not taken

    advantage of the majority of their features. Classes are substantially more powerful than the limited

    ones presented so far.

    The General Form of a Class

    When you define a class, you declare the data that it contains and the code that operates on

    it. While very simple classes might contain only code or only data, most real-world classes contain

    both. In general terms, data is contained in data membersdefined by the class, and code is contained

    infunction members. It is important to state at the outset that C# defines several specific flavors of

    data and function members. A class is created by use of the keyword class. Here is the general form of

    a simple classdefinition that contains only instance variables and methods:

    class classname

    {

    access type var1;

    access type var2;

    ...

    access type varN;

    access ret-type method1(parameters) {

    body of method

    }

    access ret-type method2(parameters) {

    body of method

  • 8/10/2019 11-06-25-11-23-51-966-carun

    2/67

    }

    ...

    access ret-type methodN(parameters) {

    body of method

    } }

    Notice that each variable and method declaration is preceded with access.Here, accessis an access

    specifier, such as public, which specifies how the member can be accessed.

    Defining a Class

    To illustrate classes, we will be evolving a class that encapsulates information about buildings, such as

    houses, stores, offices, and so on. This class is called Building, and it will store three items of

    information about a building: the number of floors, the total area, and the number of occupants.

    In general, you can use the dot operator to access both instance variables and methods. Here is a

    complete program that uses the Buildingclass:

    using System;

    class Building {

    public int floors;

    public int area;

    public int occupants;

    }

    class BuildingDemo {

    public static void Main() {

    Building house = new Building();

    int areaPP;

    house.occupants = 4;

    house.area = 2500;

    house.floors = 2;

    areaPP = house.area

    Console.WriteLine("house has:\n " +

    house.floors + " floors\n " +

    house.occupants + " occupants\n " +

    house.area + " total area\n " +

    areaPP + " area per person");

    }

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    3/67

    using System;

    class Building {

    public int floors;

    public int area;

    public int occupants; }

    class BuildingDemo {

    public static void Main() {

    Building house = new Building();

    Building office = new Building();

    int areaPP;

    house.occupants = 4;

    house.area = 2500;house.floors = 2;

    office.occupants = 25;

    office.area = 4200;

    office.floors = 3;

    areaPP = house.area

    Console.WriteLine("house has:\n " +

    house.floors + " floors\n " +

    house.occupants + " occupants\n " +

    house.area + " total area\n " +

    areaPP + " area per person");

    Console.WriteLine();

    areaPP = office.area / office.occupants;

    Console.WriteLine("office has:\n " +

    office.floors + " floors\n " +

    office.occupants + " occupants\n " +

    office.area + " total area\n " +

    areaPP + " area per person");

    }

    }

    How Objects are Created

    In the preceding programs, the following line was used to declare an object of type Building:

  • 8/10/2019 11-06-25-11-23-51-966-carun

    4/67

    uilding house = new Building();

    Methods

    As explained, instance variables and methods are two of the primary constituents of classes. So

    far, the Buildingclass contains data, but no methods. Although data-only classes are perfectly valid,

    most classes will have methods. Methodsare subroutines that manipulate the data defined by the class

    and, in many cases, provide access to that data. Typically, other parts of your program will interact

    with a class through its methods.

    The general form of a method is shown here:

    access ret-type name(parameter-list) {

    body of method

    }

    Returning a Value

    Although methods with a return type of voidare not rare, most methods will return a value. In

    fact, the ability to return a value is one of the most useful features of a method. Whatever the

    purpose, using method return values is an integral part of C# programming. Methods return a value to

    the calling routine using this form of return:

    return value;

    Here, valueis the value returned.

    Using Parameters

    It is possible to pass one or more values to a method when the method is called. As explained,

    a value passed to a method is called an argument. Inside the method, the variable that receives the

    argument is called a parameter. Parameters are declared inside the parentheses that follow the

    methods name. The parameter declaration syntax is the same as that used for variables. A parameter

    is within the scope of its method, and aside from its special task of receiving an argument, it acts like

    any other local variable.

    using System;

    class ChkNum {

    public bool isPrime(int x) {

    for(int i=2; i

  • 8/10/2019 11-06-25-11-23-51-966-carun

    5/67

    }

    class ParmDemo {

    public static void Main() {

    ChkNum ob = new ChkNum();

    for(int i=1; i < 10; i++)

    if(ob.isPrime(i)) Console.WriteLine(i + " is prime.");

    else Console.WriteLine(i + " is not prime.");

    }

    }

    Use ref

    The ref parameter modifier causes C# to create a call-by-reference, rather than a call-byvalue.

    The ref modifier is specified when the method is declared and when it is called. Lets begin with a

    simple example. The following program creates a method called Sqr( ) that returns in-place the square

    of its integer argument. Notice the use and placement of ref.

    // Use ref to pass a value type by reference.

    using System;

    class RefTest {

    // This method changes its argument. Notice the use of ref.

    public void Sqr(ref int i) {

    i = i * i;

    }

    }

    class RefDemo {

    static void Main() {

    RefTest ob = new RefTest();

    int a = 10;

    Console.WriteLine("a before call: " + a);

    ob.Sqr(ref a); // notice the use of ref

    Console.WriteLine("a after call: " + a);

    }

    }

    Notice that ref precedes the entire parameter declaration in the method and that it precedes

    the argument when the method is called. The output from this program, shown here, confirms

  • 8/10/2019 11-06-25-11-23-51-966-carun

    6/67

    that the value of the argument, a, was indeed modified by Sqr( ):

    a before call: 10

    a after call: 100

    Use Out Parameter

    An out parameter is similar to a ref parameter with this one exception: It can only be used to pass a

    value out of a method. It is not necessary (or useful) to give the variable used as an out parameter an initial

    value prior to calling the method. The method will give the variable a value. Furthermore, inside the

    method, an out parameter is considered unassigned; that is, it is assumed to have no initial value. This

    implies that the method must assign the parameter a value prior to the methods termination. Thus, after

    the call to the method, an out parameter will contain a value.

    Here is an example that uses an out parameter. In the class Decompose, the GetParts( ) method

    decomposes a floating-point number into its integer and fractional parts. Notice how each component isreturned to the caller.

    // Use out.

    using System;

    class Decompose {

    /* Decompose a floating-point value into its

    integer and fractional parts. */

    public int GetParts(double n, out double frac) {

    int whole;

    whole = (int) n;frac = n - whole; // pass fractional part back through frac

    return whole; // return integer portion

    }

    }

    class UseOut {

    static void Main() {

    Decompose ob = new Decompose();

    int i;

    double f;

    i = ob.GetParts(10.125, out f);

    Console.WriteLine("Integer portion is " + i);

    Console.WriteLine("Fractional part is " + f);

    }

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    7/67

    The output from the program is shown here:

    Integer portion is 10

    Fractional part is 0.125

    Use a Variable Number of Arguments

    The params modifier is used to declare an array parameter that will be able to receive zero or

    more arguments. The number of elements in the array will be equal to the number of arguments

    passed to the method. Your program then accesses the array to obtain the arguments. Here is an

    example that uses params to create a method called MinVal( ), which returns the minimum value from

    a set of values:

    // Demonstrate params.

    using System;

    class Min {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.Length; i++)

    if(nums[i] < m) m = nums[i];

    return m;

    }

    }

    class ParamsDemo {

    static void Main() {

    Min ob = new Min();

    int min;

    int a = 10, b = 20;

    // Call with 2 values.

    min = ob.MinVal(a, b);

    Console.WriteLine("Minimum is " + min);

    // Call with 3 values.

    min = ob.MinVal(a, b, -1);

    Console.WriteLine("Minimum is " + min);

  • 8/10/2019 11-06-25-11-23-51-966-carun

    8/67

    // Call with 5 values.

    min = ob.MinVal(18, 23, 3, 14, 25);

    Console.WriteLine("Minimum is " + min);

    // Can call with an int array, too.

    int[] args = { 45, 67, 34, 9, 112, 8 };

    min = ob.MinVal(args);

    Console.WriteLine("Minimum is " + min);

    }

    }

    The output from the program is shown here:

    Minimum is 10

    Minimum is -1

    Minimum is 3

    Minimum is 8

    Each time MinVal( ) is called, the arguments are passed to it via the nums array. The length of the

    array equals the number of elements. Thus, you can use MinVal( ) to find the minimum of any number

    of values. Notice the last call to MinVal( ). Rather than being passed the values individually, it is

    passed an array containing the values. This is perfectly legal. When a params parameter is created, it

    will accept either a variable-length list of arguments or an array containing the arguments.

    Constructors

    A constructorinitializes an object when it is created. It has the same name as its class and is

    syntactically similar to a method. However, constructors have no explicit return type. The general form

    of constructor is shown here:

    access class-name( ) {

    constructor code

    }

    Here is a simple example that uses a constructor:

    using System;

    class MyClass {

    public int x;

    public MyClass() {

    x = 10;

    }

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    9/67

    class ConsDemo {

    public static void Main() {

    MyClass t1 = new MyClass();

    MyClass t2 = new MyClass();

    Console.WriteLine(t1.x + " " + t2.x);

    }

    }

    Destructors

    It is possible to define a method that will be called prior to an objects final destruction by the

    garbage collector. This method is called a destructor,and it can be used to ensure that an object

    terminates cleanly. For example, you might use a destructor to make sure that an open file owned by

    that object is closed.

    Destructors have this general form:~class-name( ) {

    destruction code

    }

    Here, class-nameis the name of the class. Thus, a destructor is declared like a constructor except that

    it is preceded with a ~ (tilde). Notice it has no return type.

    using System;

    class Destruct {

    public int x;

    public Destruct(int i) {

    x = i;

    }

    ~Destruct() {

    Console.WriteLine("Destructing " + x);

    }

    public void generator(int i) {

    Destruct o = new Destruct(i);

    }

    }

    class DestructDemo {

    public static void Main() {

    int count;

    Destruct ob = new Destruct(0);

    for(count=1; count < 100000; count++)

  • 8/10/2019 11-06-25-11-23-51-966-carun

    10/67

    ob.generator(count);

    Console.WriteLine("Done");

    }

    }

    The this Keyword

    Before concluding this chapter, it is necessary to introduce this. When a method is called, it is

    automatically passed an implicit argument that is a reference to the invoking object (that is, the

    object on which the method is called).

    using System;

    class Rect {

    public int width;

    public int height;

    public Rect(int w, int h) {

    this.width = w;this.height = h;

    }

    public int area() {

    return this.width * this.height;

    }

    }

    class UseRect {

    public static void Main() {

    Rect r1 = new Rect(4, 5);

    Rect r2 = new Rect(7, 9);

    Console.WriteLine("Area of r1: " + r1.area());

    Console.WriteLine("Area of r2: " + r2.area());

    }

    }

    Summary

    We have seen how to declare static and instance fields, properties, methods, and constructors. We

    have also seen that C# adds some new features not present in the OOP model of some other languages:

    Static constructors provide a means of initializing static fields, while structs allow you to define high-

    performance types, albeit with a more restricted feature set, which do not require the use of the

    managed heap. We have also seen how all types in C# derive ultimately from the type System.Object,

    which means that all types start with a basic set of useful methods, including ToString()

  • 8/10/2019 11-06-25-11-23-51-966-carun

    11/67

    C#s Access Modifiers

    Member access control is achieved through the use of four access modifiers: public, private,

    protected, and internal. In this chapter we will be concerned with publicand private. The protected

    modifier applies only when inheritance is involved. The internalmodifier applies mostly to the use of

    an assembly,which for C# loosely means a deployable program or library. When a member of a class is

    modified by the public specifier, that member can be accessed by any other code in your program.

    This includes methods defined inside other classes.

    When a member of a class is specified as private, that member can be accessed only by other members

    of its class. Thus, methods in one class are not able to access a privatemember of another class. If no

    access specifier is used, a class member is private to its class by default. Thus, the privatespecifier is

    optional when creating private class members.

    An access specifier precedes the rest of a members type specification. That is, it must begin a

    members declaration statement. Here are some examples:

    public string errMsg;private double bal;

    private bool isError(byte status) { // ...

    To understand the difference between publicand private, consider the following program:

    using System;

    class MyClass {

    private int alpha;

    int beta;

    public int gamma;

    public void setAlpha(int a) {

    alpha = a;

    }

    public int getAlpha() {

    return alpha;

    }

    public void setBeta(int a) {

    beta = a;

    }

    public int getBeta() {

    return beta;

    }

    }

    class AccessDemo {

  • 8/10/2019 11-06-25-11-23-51-966-carun

    12/67

    public static void Main() {

    MyClass ob = new MyClass();

    ob.setAlpha(-99);

    ob.setBeta(19);

    Console.WriteLine("ob.alpha is " + ob.getAlpha());

    Console.WriteLine("ob.beta is " + ob.getBeta());

    ob.gamma = 99;

    }

    }

    Applying Public and Private Access

    The proper use of public and private access is a key component of successful object-oriented

    programming. Although there are no hard and fast rules, here are some general principles that serve as

    guidelines:

    1.

    Members of a class that are used only within the class itself should be private.2.

    Instance data that must be within a specific range should be private, with access provided

    through public methods that can perform range checks.

    3. If changing a member can cause an effect that extends beyond the member itself (that is,

    affects other aspects of the object), that member should be private, and access to it should be

    controlled.

    4. Members that can cause harm to an object when improperly used should be private. Access to

    these members should be through public methods that prevent improper usage.

    5.

    Methods that get and set the values of private data must be public.

    6.

    Public instance variables are permissible when there is no reason for them to be private.

    Method Overloading

    In C#, two or more methods within the same class can share the same name, as long as their

    parameter declarations are different. When this is the case, the methods are said to be overloaded,

    and the process is referred to as method overloading.Method overloading is one of the ways that C#

    implements polymorphism.

    using System;

    class Overload {

    public void ovlDemo() {

    Console.WriteLine("No parameters");

    }

    public void ovlDemo(int a) {

    Console.WriteLine("One parameter: " + a);

  • 8/10/2019 11-06-25-11-23-51-966-carun

    13/67

    }

    public int ovlDemo(int a, int b) {

    Console.WriteLine("Two parameters: " + a + " " + b);

    return a + b;

    }

    public double ovlDemo(double a, double b) {

    Console.WriteLine("Two double parameters: " +

    a + " " + b);

    return a + b;

    }

    }

    class OverloadDemo {

    public static void Main() {

    Overload ob = new Overload();int resI;

    double resD;

    ob.ovlDemo();

    Console.WriteLine();

    ob.ovlDemo(2);

    Console.WriteLine();

    resI = ob.ovlDemo(4, 6);

    Console.WriteLine("Result of ob.ovlDemo(4, 6): " + resI);

    Console.WriteLine();

    resD = ob.ovlDemo(1.1, 2.32);

    Console.WriteLine("Result of ob.ovlDemo(1.1, 2.32): " + resD);

    }

    }

    Overloading Constructors

    Like methods, constructors can also be overloaded. Doing so allows you to construct objects in

    a variety of ways. For example, consider the following program:

    using System;

    class MyClass {

    public int x;

    public MyClass() {

    Console.WriteLine("Inside MyClass().");

  • 8/10/2019 11-06-25-11-23-51-966-carun

    14/67

    x = 0;

    }

    public MyClass(int i) {

    Console.WriteLine("Inside MyClass(int).");

    x = i;

    }

    public MyClass(double d) {

    Console.WriteLine("Inside MyClass(double).");

    x = (int) d;

    }

    public MyClass(int i, int j) {

    Console.WriteLine("Inside MyClass(int, int).");

    x = i * j;

    }}

    class OverloadConsDemo {

    public static void Main() {

    MyClass t1 = new MyClass();

    MyClass t2 = new MyClass(88);

    MyClass t3 = new MyClass(17.23);

    MyClass t4 = new MyClass(2, 4);

    Console.WriteLine("t1.x: " + t1.x);

    Console.WriteLine("t2.x: " + t2.x);

    Console.WriteLine("t3.x: " + t3.x);

    Console.WriteLine("t4.x: " + t4.x);

    }

    }

    The Main( ) Method

    Up to this point, you have been using one form of Main( ). However, there are several

    overloaded forms of Main( ). Some can be used to return a value, and some can receive arguments.

    Each is examined here.

  • 8/10/2019 11-06-25-11-23-51-966-carun

    15/67

    Returning Values from Main( )

    When a program ends, you can return a value to the calling process (often the operating

    system) by returning a value from Main( ). To do so, you can use this form of Main( ):

    static int Main( )

    Notice that instead of being declared void, this version of Main( )has a return type of int.

    Passing Arguments to Main( )

    Many programs accept what are called command-linearguments. A command-line argument is

    the information that directly follows the programs name on the command line when it is executed. For

    C# programs, these arguments are then passed to the Main( )method. To receive the arguments, you

    must use one of these forms of Main( ):

    static void Main(string[ ] args)

    static int Main(string[ ] args)

    For example, the following program displays all of the command-line arguments that it is called with:

    using System;

    class CLDemo {

    public static void Main(string[] args) {

    Console.WriteLine ("There are " + args.Length + " command-line arguments.");

    Console.WriteLine ("They are: ");

    for (int i=0; i < args.Length; i++)

    Console.WriteLine (args[i]);

    }

    }

    Recursion

    In C#, a method can call itself. This process is called recursion,and a method that calls itself is

    said to be recursive.In general, recursion is the process of defining something in terms of itself and is

    somewhat similar to a circular definition. The key component of a recursive method is that it contains

    a statement that executes a call to itself. Recursion is a powerful control mechanism.

    using System;

    class Factorial {

    public int factR(int n) {

    int result;

    if(n==1) return 1;

    result = factR(n-1) * n;

    return result;

  • 8/10/2019 11-06-25-11-23-51-966-carun

    16/67

    }

    public int factI(int n) {

    int t, result;

    result = 1;

    for(t=1; t

  • 8/10/2019 11-06-25-11-23-51-966-carun

    17/67

    Console.WriteLine("StaticDemo.val is " + StaticDemo.val);

    Console.WriteLine("StaticDemo.valDiv2(): " + StaticDemo.valDiv2());

    }

    }

    There are several restrictions that apply to staticmethods:

    1.

    A staticmethod does not have a thisreference.

    2. A staticmethod can directly call only other staticmethods. It cannot directly call an instance

    method of its class. The reason for this is that instance methods operate on specific instances

    of a class, but a staticmethod does not.

    3.

    A static method must directly access only static data. It cannot directly use an instance

    variable because it is not operating on an instance of its class.

    Static ConstructorsA constructor can also be specified as static. A staticconstructor is typically used to initialize

    attributes that apply to a class rather than an instance. Thus, it is used to initialize aspects of a class

    before any objects of the class are created. Here is a simple example:

    using System;

    class Cons {

    public static int alpha;

    public int beta;

    static Cons() {

    alpha = 99;

    Console.WriteLine("Inside static constructor.");

    }

    public Cons() {

    beta = 100;

    Console.WriteLine("Inside instance constructor.");

    }

    }

    class ConsDemo {

    public static void Main() {

    Cons ob = new Cons();

    Console.WriteLine("Cons.alpha: " + Cons.alpha);

    Console.WriteLine("ob.beta: " + ob.beta);

    }

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    18/67

    Static Classes

    C# 2.0 added the ability to create staticclasses. There are two key features of a staticclass.

    First, no object of a static class can be created. Second, a static class must contain only static

    members. The main benefit of declaring a class static is that it enables the compiler to prevent any

    instances of that class from being created. Thus, the addition of staticclasses does not add any new

    functionality to C#. It does, however, help prevent errors.

    A staticclass is created by modifying a class declaration with the keyword static, as shown here:

    static class class-name{ // ...

    Within the class, all members must be explicitly specified as static. Making a class static does not

    automatically make its members static.

    using System;

    static class NumericFn {static public double reciprocal(double num) {

    return 1/num;

    }}

    class StaticClassDemo {

    public static void Main() {

    Console.WriteLine("Reciprocal of 5 is " +

    NumericFn.reciprocal(5.0));

    }

    }

    Summary

    In this chapter weve examined C# syntax for declaring and manipulating objects. We have

    seen how to

    declare static and instance fields, properties, methods, and constructors. We have also seen that C#

    adds some new features not present in the OOP model of some other languages: Static constructors

    provide a means of initializing static fields, while structs allow you to define high-performance types,

    albeit with a more restricted feature set, which do not require the use of the managed heap. We have

    also seen how all types in C# derive ultimately from the type System.Object, which means that all

    types start with a basic set of useful methods, including ToString().

    Objective

    1. A variable which is declared inside a method is called a________variablea) Serial b) Local c) Private d) Static

  • 8/10/2019 11-06-25-11-23-51-966-carun

    19/67

    2. Feature of a local variablea) It can be used anywhere in the program b) It must accept a classc) It must be declared within a method d) It represent a class object

    3. Two methods with the same name but with different parameters.a) Overloading b) Loading c) Multiplexing d) Duplexing

    4. Is there any errors in this -> EmployeeMgmt constructor: Public int EmployeeMgmt { emp_id = 100; }a) Return type b) No errors c) Formal parameters d) Name

    5. If a class is using an interface, it musta) inherit the properties of the interface b) contain the same methods as the interfacec) create an interface object d) all of the above

    6. What is the output of the code public class B : A { }a) Errors b) It defines a class that inherits the public methods of A only.c) It defines a class that inherits all the methods of A but the private members cannot be accessed.d) b and c

    7. Sealed Classes cannot be a base class.a) True b) False

    8. What are the features of an abstract class?a) It contain instance variables b) It contain constructors c) It may extend another classd) all of the above

    9. Features of Read only variablesa) It is allocated at compile time b) Declaration and initialization is separatedc) It is allocated at runtime d) all of these

    10. An Event has _____ as default return typea) No return type for events b) Double c) Integer d) String

    11. int keyword targets to which .Net type?a) System.Int8 b) System.Int16 c) System.Int32 d) System.Int64

    12. How many web.config files that can be there an ASP.NET application?a) only one b) only two c) upto 10 d) more than one

    13. Difference between Convert.ToString() and ToString()a) Convert.ToString() handle null values but ToString() don'tb) ToString() output as per format suppliedc) Convert.ToString() only handle null valuesd) ToString() handle null values but Convert.ToString() don't

    INHERITENCE AND POLYMORPHISMC# classes can be reused to several ways. Reusability is achieved by designing new classes,

    reusing all or some of the properties of existing ones. The mechanism of designing or constructing one

    class from another is called inheritance.

    This may be achieved in two different forms.

    1. Classical form

    2.

    Containment form

  • 8/10/2019 11-06-25-11-23-51-966-carun

    20/67

    CLASSICAL INHERITENCE

    Inheritance represents a kind of relationship between two classes. Let us consider two classes A

    and B. We can create a class hierarchy such that B is derived from A.

    We can now create objects of classes A and B independently. Example

    A a; // a is object A

    B b; // b is object B

    In Such cases, we say that the object b is a type of a. Such relationship between a and b is

    referred to as is a relationship

    Ex:

    1. Dog is-a type animal

    2. Manager is-a type of employee

    3.

    Ford is-a type of carThe classical inheritance may be implemented in different combinations as follows

    1. Single Inheritance (Only One Base Class)

    2. Multiple Inheritance (Several Base Classes)

    3.

    Hierarchical Inheritance ( One Base Class, many subclass)

    4.

    Multilevel Inheritance (Derived from a Derived class)

    C# does not directly implement multiple inheritances. However, this concept is implemented

    using a secondary inheritance path in the form of interfaces.

    CONTAINMENT INHERITANCE

    We can also define another form of inheritance relationship known as containership between

    class A and B.

    Example:

    class A

    {

    ---------

    }

    class B

    {

    ---------

    A a; // a is contained in b

    }

    B b;

    ---------

  • 8/10/2019 11-06-25-11-23-51-966-carun

    21/67

    In such cased, we say that the object a is contained in the object b. This relationship between

    a and b is referred to as has-a relationship. The outer class B which contains the inner class A is

    termed the parent class and the contained class A is termed a child class.

    Ex:

    1.

    Car has-a redio

    2.

    House has-a store room

    3.

    City has-a road

    DEFINING A SUBCLASS

    Syntax:

    class subclass-name : baseclass-name

    {

    Variable declaration;

    Methods declaration;}

    Example program for the Simple Inheritance

    usingSystem;

    classItem

    {

    publicvoidCompany ()

    {

    Console.WriteLine ("Item Code = XXX");

    }

    }

    classFan:Item

    {

    publicvoidModel()

    {

    Console.WriteLine ("Fan Model : Classic");

    }

    }

    classSimpleInheritance

    {

    publicstaticvoidMain()

    {

    Item item = newItem ();

    Fan fan = newFan ();

  • 8/10/2019 11-06-25-11-23-51-966-carun

    22/67

    item.Company ();

    fan.Company ();

    fan.Model ();

    }

    }

    Note:

    Inheritance is transitive.

    (i) class A : B

    {

    }

    class B : C

    {

    }class C : A

    {

    }

    (ii)

    class A

    {

    Class B : A

    {

    }

    }

    Some important characteristics of Inheritance are:

    1.

    A derived class extends its direct base class. It can add new members to those it inherits.

    However, it cannot change or remove the definition on an inherited member.

    2. Constructor and destructors are not inherited. All other members, regardless of their

    declared accessibility in base class, are inherited.

    3. All instance of a class contains a copy of all instance fields declared in the class and its

    base classes.

    4.

    A derived class can hide an inherited member.

    5. A derived class can override an inherited member.

    CLASS VISIBILTY AND CLASS MEMBER VISIBILTY CONTROL

  • 8/10/2019 11-06-25-11-23-51-966-carun

    23/67

    Keyword Containing

    Classes

    Derived Classes Containing Program Anywhere outside the

    containing program

    private YES NO NO NO

    Protected YES YES NO NO

    Internal YES NO YES NO

    protected

    internal

    YES YES YES NO

    public YES YES YES YES

    ACCESIIBILITY DOMAIN OF CLASS MEMBERS

    Member modifier Public Internal Private

    public Every where Only Program Only class

    internal Only program Only program Only class

    private Only class Only class Only class

    Accessibility of Baseclass Members

    class A

    {

    private int x;

    protected int y;

    public int z;

    }class B : A

    {

    public void SetXYZ ()

    {

    X = 10; // Error; x is not accessible

    Y = 20; //ok

    Z = 30; //ok

    }

    }

    A a = new A ( ); // Object of A

    a.y = 5;

    a.z = 34;

  • 8/10/2019 11-06-25-11-23-51-966-carun

    24/67

    Accessibility Constraints

    1.

    The direct base class of a derived class must be at least as accessible as the derived class

    itself.

    2. Accessibility domain of a member is never larger than that of the class containing it.

    3.

    The return type of method must be atleast as accessible as the method itself

    Case 1

    class A

    {

    ---------

    }

    public class B : A

    {

    --------}

    Case 2 : Class A

    {

    Private class B

    {

    Public int x;

    }

    }

    Case 3 : Class A

    {

    ---------

    }

    Public class B

    {

    A method1() { }

    Internal A Method2 ( ) { }

    Public A Method3 ( ) { }

    }

    // APPLICATION OF SINGLE INHERITANCE

    usingSystem;

    classRoom1

  • 8/10/2019 11-06-25-11-23-51-966-carun

    25/67

    {

    publicintlength;

    publicintbreadth;

    publicRoom1(intx,inty)

    {

    length = x;

    breadth = y;

    }

    publicintArea ()

    {

    return(length * breadth);

    }

    }

    classRoom2 : Room1{ intheight;

    publicRoom2 (intx,inty,intz) : base(x,y)

    {

    height = z;

    }

    publicintVolume()

    {

    return(length * breadth * height);

    }

    }

    classInherTest

    {

    publicstaticvoidMain()

    { Room2 room2 = newRoom2 (14,12,10);

    intarea1 = room2.Area ();

    intvolume1 = room2.Volume ();

    Console.WriteLine ("Area = " + area1);

    Console.WriteLine ("Volume = " + volume1);

    }

    }

    MULTILEVEL INHERITENCE

    // APPLICATION OF MULTILEVEL INHERITANCE

    usingSystem;

  • 8/10/2019 11-06-25-11-23-51-966-carun

    26/67

    classA

    {

    protectedinta;

    publicA (intx)

    {

    a = x;

    }

    publicvoiddisplay_one()

    {

    Console.WriteLine ("The A Value is: " + a);

    }

    }

    classB:A

    {protectedintb;

    publicB (intx,inty):base(x)

    {

    b = y;

    }

    publicvoiddisplay_two()

    {

    Console.WriteLine ("The A Value is: " + a);

    Console.WriteLine ("The B Value is: " + b);

    }

    }

    classC:B

    {

    intc;

    publicC (intx,inty,intz):base(x,y)

    {

    c = z;

    }

    publicvoiddisplay_three()

    {

    Console.WriteLine ("The A Value is: " + a);

    Console.WriteLine ("The B Value is: " + b);

    Console.WriteLine ("The C Value is: " + c);

  • 8/10/2019 11-06-25-11-23-51-966-carun

    27/67

  • 8/10/2019 11-06-25-11-23-51-966-carun

    28/67

    classSub_Two:Super

    {

    protectedintz,z1;

    publicSub_Two(intx,intz):base(x)

    {

    this.z = z;

    }

    publicvoiddisplay_sub_two()

    {

    z1 = x + z;

    Console.WriteLine ("The Addition of the Two Numbers:" + z1);

    }

    }

    classMainSuper{

    publicstaticvoidMain()

    {

    Sub_One so = newSub_One (15,12);

    Sub_Two st = newSub_Two (45,23);

    so.display_sub_one ();

    st.display_sub_two ();

    }

    }

    Summary

    C# offers rich support for both multiple interface and single implementation inheritance, as

    well as provides a number of useful syntactical constructs designed to assist in making code more

    robust, such as the override keyword, which indicates when a function should override a base function;

    the new keyword, which indicates when a function hides a base function; and the rigid rules for

    constructor initializes that are designed to ensure that constructors are designed to interoperate in a

    robust manner.

    OVERRIDING METHODS

    We have seen that a method defined in a super class is inherited by its subclass and is used by

    the objects created by the subclass. Method inheritance enables us to define and use methods

    repeatedly in sub classes.

  • 8/10/2019 11-06-25-11-23-51-966-carun

    29/67

    However, there may be occasions when we want an object to respond to the same method but

    behave differently when that method is called. That means, we should override the method defined in

    the super class. This is possible by defining a method in the subclass that has the same name, same

    arguments and same return type as a method in the super class. Then, when that method is called, the

    method defined in the subclass is invoked and executed instead of the one in the super class, provided

    that

    1. We specify the method in base class as virtual

    2. Implement the method in subclass using the keyword override

    This is known as overriding

    Note:

    1. An override declaration may include the abstractmodifier.

    2. It is an error for an override declaration to include newor staticor virtualmodifier.

    3.

    The overridden base method cannot be staticor non-virtual.4.

    The overridden base method cannot be a sealedmethod.

    // APPLICATION OF METHOD OVERRIDING

    usingSystem;

    classSuper

    {

    protectedintx;

    publicSuper (intx)

    {

    this.x = x;

    }

    publicvirtualvoidDisplay()

    {

    Console.WriteLine ("Super x = " + x);

    }

    }

    classSub:Super

    {

    inty;

    publicSub(intx,inty):base(x)

    {

    this.y = y;

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    30/67

    publicoverridevoidDisplay()

    {

    Console.WriteLine ("Super x = " + x);

    Console.WriteLine ("Sub y = " + y);

    }

    }

    classOverrideTest

    {

    publicstaticvoidMain()

    {

    Sub s1 = newSub (100,200);

    s1.Display ();

    }

    }

    HIDING METHODS

    Now, let us assume that we wish to derive from a class provided by someone else and we also

    want to redefine some methods contained in it. Here, we cannot declare the base class methods as

    virtual. Then, how do we override a method without declaring it virtual? This is possible in C#. We can

    use the modifier new to tell the compiler that the derived class method hides the base class method.

    // HIDING A BASE CLASS METHOD

    usingSystem;

    classBase

    {

    publicvoidDisplay()

    {

    Console.WriteLine ("Base Method");

    }

    }

    classDerived:Base

    {

    publicnewvoidDisplay ()

    {

    Console.WriteLine ("Derived Method");

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    31/67

    }

    classHideTest

    {

    publicstaticvoidMain()

    {

    Derived d = newDerived ();

    d.Display ();

    }

    }

    ABSTRACT CLASSES

    In a number of hierarchical applications, we would have one base class and a number of

    different derived classes. The top most base class simply acts as a base for others and is not useful on

    its own. In such situations, we might not want any one to create its objects. E can do this by makingthe base class abstract

    Some Characteristics of an abstract class are:

    1. It cannot be instantiated directly.

    2.

    It can have abstract members.

    3.

    We cannot apply a sealed modifier to it.

    // ABSTRACT CLASSES

    usingSystem;

    abstract/*sealed*/classBase

    {

    protectedintx = 23;

    //Console.WriteLine ("The X Value is: " + x);

    }

    classDerived:Base

    {

    publicvoidDisplay ()

    {

    Console.WriteLine ("The X Value is: " + x);

    }

    }

    classHideTest

    {

    publicstaticvoidMain()

    {

  • 8/10/2019 11-06-25-11-23-51-966-carun

    32/67

    //Base b = new Base ();

    Derived d = newDerived ();

    d.Display ();

    }

    }

    ABSTRACT METHODS

    Similar to abstract classes, we can also create abstract methods. When an instance method

    declaration includes the modifier abstract, the method is said to be an abstract method.

    An abstract method is implicitly a virtual method and does not provide any implementation.

    Some Characteristics of an abstract method are:

    1. It cannot have implementation.

    2.

    Its implementation must be provided in non abstract derived classes by overriding themethod.

    3. It can be declared only in abstract classes.

    4. It cannot take either staticor virtualmodifiers

    5.

    An abstract declaration is permitted to override a virtual method.

    // ABSTRACT CLASSES AND ABSTRACT METHODS

    usingSystem;

    abstractclassBase

    {

    publicabstractvoidDraw ();

    }

    classDerived:Base

    {

    publicoverridevoidDraw ()

    {

    Console.WriteLine ("This is Draw");

    }

    }

    classHideTest

    {

    publicstaticvoidMain()

    {

    Derived d = newDerived ();

  • 8/10/2019 11-06-25-11-23-51-966-carun

    33/67

    d.Draw ();

    }

    }

    // SEALED CLASSES: PREVENTING INHERITANCE

    usingSystem;

    sealedclassA

    {

    protectedintx;

    }

    sealedclassB:A

    {

    publicvoiddisplay()

    {x = 34;

    Console.WriteLine ("The X Value is :" + x);

    }

    }

    classMainSealed

    {

    publicstaticvoidMain()

    {

    B b = newB ();

    b.display ();

    }

    }

    // SEALED METHOD

    usingSystem;

    classA

    {

    publicvirtualvoiddisplay()

    {

    Console.WriteLine ("Welcome_One");

    }

    }

    classB:A

    {

  • 8/10/2019 11-06-25-11-23-51-966-carun

    34/67

    publicsealedoverridevoiddisplay()

    {

    Console.WriteLine ("Welcome_Two");

    }

    }

    classC:B

    {

    publicoverridevoiddisplay()

    {

    Console.WriteLine ("Welcome_Three");

    }

    }

    classMainSealed{

    publicstaticvoidMain()

    {

    C c = newC ();

    c.display ();

    }

    }

    POLYMORPHISM

    Polymorphism mean one name, many forms, essentially, polymorphism is the capability of

    one object to behave in multiple ways.

    Polymorphism

    InclusionPolymorphism

    OperationPolymorphism

    Usingoverloaded

    Using virtual

    method

  • 8/10/2019 11-06-25-11-23-51-966-carun

    35/67

    OPERATION POLYMORPHISM

    The overloaded methods are selected for invoking by matching arguments, in terms of

    number, type and order. This information is known to the compiler at the time of compilation and,

    therefore, the compiler is able to select and bind the appropriate method to the object for a particular

    call at compile time itself. This process is called early binding, or static binding, or static linking. It is

    also known as compiling time polymorphism.

    Early binding simply means that an object is bound to its method call at compile time.

    // OPERATION POLYMORPHISM

    usingSystem;

    classDog

    { }

    classCat

    { }classOperation

    {

    staticvoidCall (Dog d)

    {

    Console.WriteLine ("Dog is Called");

    }

    staticvoidCall (Cat c)

    {

    Console.WriteLine ("Cat is Called");

    }

    publicstaticvoidMain()

    {

    Dog dog = newDog ();

    Cat cat = newCat ();

    Call(dog);

    Call(cat);

    }

    }

    CASTING BETWEEN TYPES

    One of the important aspects in the application of inheritance, namely, type casting between

    classes. There are a number of situations where we need to apply casting between the objects of base

  • 8/10/2019 11-06-25-11-23-51-966-carun

    36/67

    and derived classes. C# permits upcasting of an object of a derived class to an object of its base class.

    However, we cannot downcast implicitly an object of a base class to an object of the derived classes.

    class Base

    { }

    Class Derived:Base

    { }

    Base b = new Derived ( ); // Upcasting

    Derived d = new Base ( ); //Downcasting, Error.

    INCLUSION POLYMORPHISM

    Inclusion polymorphism is achieved through the use of virtual functions. Assume that the class

    A implements a virtual method M and classes B and C that are derived from A override the virtual

    method M. When B is cast to A, a call to the method M from A is dispatched to B. Similarly, when C is

    cast to A, a call to M is dispatched to C. The decision on exactly which method to call is delayed untilruntime and, therefore, it is also known as runtime polymorphism. Since the method is linked with a

    particular class much later after compilation, this process is termed late binding. It is also known as

    dynamic binding, because the selection of the appropriate method is done dynamically at runtime.

    // INCLUSION POLYMORPHISM

    usingSystem;

    classMaruthi

    {

    publicvirtualvoidDisplay ()

    {

    Console.WriteLine ("Maruthi Car");

    }

    }

    classEsteem:Maruthi

    {

    publicoverridevoidDisplay()

    {

    Console.WriteLine ("Maruthi Esteem");

    }

    }

    classZen:Maruthi

    {

    publicoverridevoidDisplay()

  • 8/10/2019 11-06-25-11-23-51-966-carun

    37/67

    {

    Console.WriteLine ("Maruthi Zen");

    }

    }

    classInclusion

    {

    publicstaticvoidMain()

    {

    Maruthi m = newMaruthi ();

    m = newEsteem (); //Upcasting

    m.Display ();

    m = newZen (); //UpCasting

    m.Display ();

    }}

    INTERFACES: MULTIPLE INHERITANCE

    DEFINING AN INTERFACE

    An interface can contain one or more methods, properties, indexers and events but none of

    them are implemented in the interface itself. It is the responsibility of the class that implements the

    interface to define the code for implementation of these members.

    Syntax:

    interface Interfacename

    {

    Member declarations;

    }

    Ex:

    interface Show

    {

    void Display ( );

    }

    Ex:

    interface Example

    {

    int Aproperty

    {

    get;

  • 8/10/2019 11-06-25-11-23-51-966-carun

    38/67

    }

    event someEvent Changed;

    void Display( );

    }

    The accessibility of an interface can be controlled by using the modifiers public, protected,

    internaland private.

    We may also apply the modifier newon nested interfaces. It specifies that the interface hides

    an inherited member by the same name.

    DIFFERENCE BETWEEN CLASSES AND INTERFACES

    1. All the members of an interface are implicitly publicand abstract.

    2. An interface cannot contain fields, constructors and destructors.

    3.

    Its members cannot be declared static.4.

    Since the methods in an interface are abstract, they do not include implementation code.

    5. An Interface can inherit multiple interfaces.

    EXTENDING INTERFACES

    Syntax:

    interface name2 : name1

    {

    Members of name2

    }

    Ex:

    interface Addition

    {

    int Add (int x,int y);

    }

    interface Compute : Addition

    {

    int Sub(int x, int y);

    }

    Ex:

    interface I1

    { }

    interface I2

    { }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    39/67

    interface I3 : I1, I2

    { }

    IMPLEMENTING INTERFACES

    Syntax:

    class classname : interfacename

    {

    Body of classname

    }

    class classname : superclass, interface1, interface2

    {

    Body of classname

    }

    Ex:class A : I

    { }

    class B : A, I1, I2

    { }

    IMPLEMENTATION OF MULTIPLE INTERFACES

    usingSystem;

    interfaceAddition

    {

    intAdd();

    }

    interfaceMultiplication

    {

    intMul();

    }

    class Computation:Addition,Multiplication

    {

    intx,y;

    publicComputation(intx,inty)

    {

    this.x = x;

    this.y = y;

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    40/67

    publicintAdd()

    {

    return(x+y);

    }

    publicintMul()

    {

    return(x*y);

    }

    }

    classInterfaceTest

    {

    publicstaticvoidMain()

    {

    Computation com = newComputation (10,20);Addition add = (Addition) com;

    Console.WriteLine ("Sum = " + add.Add ());

    Multiplication mul = (Multiplication) com;

    Console.WriteLine ("Product = " + mul.Mul ());

    } }

    MULTIPLE IMPLEMENTATION OF AN INTERFACE

    usingSystem;

    interfaceArea

    {

    doubleCompute(doublex);

    }

    classSquare : Area

    {

    publicdoubleCompute(doublex)

    {

    return(x*x);

    }

    }

    classCircle : Area

    {

    publicdoubleCompute(doublex)

    {

  • 8/10/2019 11-06-25-11-23-51-966-carun

    41/67

    return(Math.PI * x * x);

    }

    }

    classInterfaceTest

    {

    publicstaticvoidMain()

    {

    Square sqr = newSquare ();

    Circle cir = newCircle ();

    Area area;

    area = sqr asArea ;

    Console.WriteLine ("Area of Square = " + area.Compute (10.0));

    area = cir asArea ;Console.WriteLine ("Area of Circle = " + area.Compute (10.0));

    }

    }

    INHERITING A CLASS THAT IMPLEMENTS AN INTERFACE

    usingSystem;

    interfaceDisplay

    {

    voidPrint ();

    }

    classB : Display

    {

    publicvoidPrint ()

    {

    Console.WriteLine ("Base Display");

    }

    }

    classD : B

    {

    publicnewvoidPrint ()

    {

    Console.WriteLine ("Derived Display");

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    42/67

    }

    classInterfaceTest

    {

    publicstaticvoidMain()

    {

    D d = newD ();

    d.Print ();

    Display dis = (Display) d;

    dis.Print ();

    }

    }

    EXPLICIT INTERFACE IMPLEMENTATIONusingSystem;

    interfaceI1

    {

    voidDisplay();

    }

    interfaceI2

    {

    voidDisplay();

    }

    classC1 : I1,I2

    {

    voidI1.Display ()

    {

    Console.WriteLine ("I1 Display");

    }

    voidI2.Display ()

    {

    Console.WriteLine ("I2 Display");

    }

    }

    classInterfaceTest

    {

    publicstaticvoidMain()

  • 8/10/2019 11-06-25-11-23-51-966-carun

    43/67

    {

    C1 c = newC1 ();

    I1 i1 = (I1) c;

    i1.Display ();

    I2 i2 = (I2) c;

    i2.Display ();

    }

    }

    ABSTRACT CLASS AND INTERFACES

    usingSystem;

    interfaceA

    {

    voidDisplay();}

    abstractclassB : A

    {

    publicabstractvoidDisplay ();

    }

    classC : B

    {

    publicoverridevoidDisplay ()

    {

    Console.WriteLine ("Welcome");

    }

    }

    classInterfaceTest

    {

    publicstaticvoidMain()

    {

    C c = newC ();

    c.Display ();

    }

    }

    Operator Overloading Fundamentals

  • 8/10/2019 11-06-25-11-23-51-966-carun

    44/67

    Operator overloading is closely related to method overloading. To overload an operator, you

    use the operator keyword to define an operator method,which defines the action of the operator

    relative to its class. There are two forms of operatormethods: one for unary operators and one for

    binary operators. The general form for each is shown here:

    // General form for overloading a unary operator.

    public static ret-typeoperator op(param-type operand)

    {

    operations

    }

    // General form for overloading a binary operator.

    public static ret-typeoperator op(param-type1 operand1,param-type1 operand2)

    {

    operations

    }// An example of operator overloading.

    using System;

    class ThreeD {

    int x, y, z;

    public ThreeD() { x = y = z = 0; }

    public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }

    public static ThreeD operator +(ThreeD op1, ThreeD op2)

    {

    ThreeD result = new ThreeD();

    result.x = op1.x + op2.x;

    result.y = op1.y + op2.y;

    result.z = op1.z + op2.z;

    return result;

    }

    public static ThreeD operator -(ThreeD op1, ThreeD op2)

    {

    ThreeD result = new ThreeD();

    result.x = op1.x - op2.x;

    result.y = op1.y - op2.y;

    result.z = op1.z - op2.z;

    return result;

    }

    public void show()

  • 8/10/2019 11-06-25-11-23-51-966-carun

    45/67

    {

    Console.WriteLine(x + ", " + y + ", " + z);

    }

    }

    class ThreeDDemo {

    public static void Main() {

    ThreeD a = new ThreeD(1, 2, 3);

    ThreeD c = new ThreeD();

    a.show();

    Console.Write("Here is b: ");

    b.show();

    Console.WriteLine();

    c = a + b;Console.Write("Result of a + b: ");

    c.show();

    Console.WriteLine();

    c = a + b + c;

    Console.Write("Result of a + b + c: ");

    c.show();

    Console.WriteLine();

    c = c - a;

    Console.Write("Result of c - a: ");

    c.show();

    Console.WriteLine();

    c = c - b;

    Console.Write("Result of c - b: ");

    c.show();

    Console.WriteLine();

    }

    }

    Overloading Unary Operators

    The unary operators are overloaded just like the binary operators. The main difference, of

    course, is that there is only one operand. For example, here is a method that overloads the unary

    minus for the ThreeDclass:

    // Overload unary -.

  • 8/10/2019 11-06-25-11-23-51-966-carun

    46/67

    public static ThreeD operator -(ThreeD op)

    {

    ThreeD result = new ThreeD();

    result.x = -op.x;

    result.y = -op.y;

    result.z = -op.z;

    return result;

    }

    Here, a new object is created that contains the negated fields of the operand. This object is then

    returned. Notice that the operand is unchanged. Again, this is in keeping with the usual meaning of the

    unary minus. For example, in an expression such as this:

    a = -b

    areceives the negation of b, but bis not changed.

    There are, however, two cases in which an operator method will need to change the contents of anoperand: ++ and . Since the usual meaning of these operators is increment and decrement, an

    overloaded ++ or should usually increment or decrement the operand. Thus, when overloading

    these two operators, the operand will usually be modified. For example, here is an operator++( )

    method for the ThreeDclass:

    // Overload unary ++.

    public static ThreeD operator ++(ThreeD op)

    {

    op.x++;

    op.y++;

    op.z++;

    return op; }

    Notice that the object referred to by op is modified by this method. Thus, the operand in a ++

    operation is incremented. The modified object is also returned. This is necessary to allow the ++

    operator to be used in a larger expression.

    Here is an expanded version of the previous example program that demonstrates the unary and the

    ++operator:

    using System;

    class ThreeD {

    int x, y, z;

    public ThreeD() { x = y = z = 0; }

    public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    47/67

    public static ThreeD operator +(ThreeD op1, ThreeD op2)

    {

    ThreeD result = new ThreeD();

    result.x = op1.x + op2.x;

    result.y = op1.y + op2.y;

    result.z = op1.z + op2.z;

    return result;

    }

    public static ThreeD operator -(ThreeD op1, ThreeD op2)

    {

    ThreeD result = new ThreeD();

    result.x = op1.x - op2.x;

    result.y = op1.y - op2.y;result.z = op1.z - op2.z;

    return result;

    }

    public static ThreeD operator -(ThreeD op)

    {

    ThreeD result = new ThreeD();

    result.x = -op.x;

    result.y = -op.y;

    result.z = -op.z;

    return result;

    }

    public static ThreeD operator ++(ThreeD op)

    {

    op.x++;

    op.y++;

    op.z++;

    return op;

    }

    public void show()

    {

    Console.WriteLine(x + ", " + y + ", " + z);

    }

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    48/67

    class ThreeDDemo {

    public static void Main() {

    ThreeD a = new ThreeD(1, 2, 3);

    ThreeD b = new ThreeD(10, 10, 10);

    ThreeD c = new ThreeD();

    Console.Write("Here is a: ");

    a.show();

    Console.WriteLine();

    Console.Write("Here is b: ");

    b.show();

    Console.WriteLine();

    c = a + b;

    Console.Write("Result of a + b: ");

    c.show();Console.WriteLine();

    c = a + b + c;

    Console.Write("Result of a + b + c: ");

    c.show();

    Console.WriteLine();

    c = c - a;

    Console.Write("Result of c - a: ");

    c.show();

    Console.WriteLine();

    c = c - b;

    Console.Write("Result of c - b: ");

    c.show();

    Console.WriteLine();

    c = -a;

    Console.Write("Result of -a: ");

    c.show();

    Console.WriteLine();

    a++;

    Console.Write("Result of a++: ");

    a.show();

    }

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    49/67

    DELEGATES AND EVENTS

    Introduction

    In object oriented programming, one object to send messages to other objects. However, in

    real life applications, it is quite common for an object to report back to the object that was

    responsible for sending a message. This, in effect, results in a two way conversation between objects.

    Language like C and C++ implement callback techniques using what are known as function

    pointers. Function pointers simply represent memory addresses and they do not include type safe

    information such as

    Number of parameters

    Types of parameters

    Return type and

    Calling convention

    Further, in object oriented programming, methods rarely exist in isolation. They are usually

    associated with a class instance before they can be called. Because of these problems. C# implements

    the callback technique in a much safer and more object oriented manner, using a kind of object

    called delegate object.

    A delegate object is a special type of object that contains the details of a method

    rather than data.

    Delegates in C# are used for two purposes:

    1.

    Callback

    2.

    Event Handling

    DELEGATES

    Delegate is a person acting for another person. In C#, it really means a method acting for

    another method. A delegate in C# is a class type object and is used to invoke a method that has been

    encapsulated into it at the time of its creation. Creating and using delegates involve four steps. They

    include:

    1. Delegate declaration

    2.

    Delegate methods definition

    3.

    Delegate instantiation

    4. Delegate invocation

    A delegate declaration defined a class using the class System. Delegate as a base class.

    DELEGATE DECLARATION

  • 8/10/2019 11-06-25-11-23-51-966-carun

    50/67

    modifier delegatereturn-type delegate-name (parameter)

    modifier new, public, protected, private, internal

    Ex:

    delegate void SimpleDelegate( );

    delegate int MathOperation(int x,int y);

    public delegate int CompareItems(Object o1,Object o2);

    Delegate may be defined in the following places:

    1. Inside a class.

    2.

    Outside all class.

    3.

    As the top level object in a namespace.

    Delegate types are implicitly sealed and therefore it is not possible to derive any type from a delegate

    type.

    DELEGATE METHOD

    The methods whose references are encapsulated into a delegate instance are known as

    delegate methods or callable entities. The signature and return type of delegate methods must exactly

    match the signature and return type of the delegate.

    delegate void Delegate1( );

    public void F1( )

    {

    Console.WriteLine (F1);

    }

    static public void F2 ( )

    {

    Console.WriteLine (F2);

    }

    DELEGATE INSTANTATION

    A delegate creation-expression is used to create a new instance of a delegate.

    new delegate-type (expression);

    DELEGATE INVOCATION

    delegate_object (parameters_list);

    usingSystem;

  • 8/10/2019 11-06-25-11-23-51-966-carun

    51/67

    //delegate declaration

    delegateintArithOp(intx,inty);

    classMathOperation

    {

    //delegate methods definition

    publicstaticintAdd(inta,intb)

    {

    return(a + b);

    }

    publicstaticintSub(inta,intb)

    {

    return(a - b);

    }

    }classDelegateTest

    {

    publicstaticvoidMain()

    {

    ArithOp operation1 = newArithOp (MathOperation.Add );

    ArithOp operation2 = newArithOp (MathOperation.Sub );

    intresult1 = operation1(200,100);

    intresult2 = operation2(200,100);

    Console.WriteLine ("Result1 = " + result1);

    Console.WriteLine ("Result2 = " + result2);

    }

    }

    MULTICAST DELEGATES

    Single Delegate can invoke only one method. However, it is possible for certain delegates to

    hold and invoke multiple methods. Such delegates are called multicast delegates, also known as

    combinable delegates.

    1.

    The return type of the delegates must be void

    2.

    None of the parameters of the delegate type can be declared as output parameter, using

    out keyword.

    usingSystem;

  • 8/10/2019 11-06-25-11-23-51-966-carun

    52/67

    delegatevoidMDelegate();

    classDM

    {

    staticpublicvoidDisplay()

    {

    Console.WriteLine ("NEW DELHI");

    }

    staticpublicvoidPrint()

    {

    Console.WriteLine ("NEW YORK");

    }

    }

    classMTest

    {publicstaticvoidMain()

    {

    MDelegate m1 = newMDelegate (DM.Display );

    MDelegate m2 = newMDelegate (DM.Print );

    MDelegate m3 = m1 + m2;

    MDelegate m4 = m2 + m1;

    MDelegate m5 = m3 - m2;

    m3();

    m4();

    m5();

    }

    }

    EVENTS

    An event is a delegate type class member that is used by the object or class to provide a

    notification to other objects that a event has occurred. The client object can act on an event by

    adding an event handler to the event.

    Events are declared using the simple event declaration format as follows:

    modifier event type event-name;

    The modifier may be new, a valid combination of the four access modifiers, and a valid

    combination of static, virtual, override and sealed. The type of an event declaration must be a

    delegate type and the delegate must be as accessible as the event itself.

    Ex:

  • 8/10/2019 11-06-25-11-23-51-966-carun

    53/67

    public event EventHandler Click;

    public event RateChange Rate;

    EventHandler and RateChange are delegates and Click and Rate are events.

    usingSystem;

    //delegate declaration first

    publicdelegatevoidEDelegate(stringstr);

    classEventClass

    {

    //declaration of event

    publiceventEDelegate Status;

    publicvoidTriggerEvent()

    {

    if(Status != null)

    Status("Event Triggered");}

    }

    classEventTest

    {

    publicstaticvoidMain()

    {

    EventClass ec = newEventClass ();

    EventTest et = newEventTest ();

    ec.Status += newEDelegate (et.EventCatch);

    ec.TriggerEvent ();

    }

    publicvoidEventCatch(stringstr)

    {

    Console.WriteLine (str);

    }

    }

    Summary

    This chapter gave you the basics of delegates and events. We explained how to declare a

    delegate and add methods to the delegate list. We also explained the process of declaring event

    handlers to respond to an event, as well as how to create a custom event and use the patterns for

    raising the vent. As a .NET developer, you will be using delegates and events extensively, especially

    when developing Windows Forms applications. Events are the means that the .NET developer has to

  • 8/10/2019 11-06-25-11-23-51-966-carun

    54/67

    monitor the various Windows messages that occur while the application is executing. Otherwise you

    would have to monitor the WndProc and catch the WM_MOUSEDOWN message instead of getting the

    mouse Click event for a button. The use of delegates and events in the design of a large application

    can reduce dependencies and the coupling of layers. This allows you to develop components that have

    a higher reusability factor.

    INDEXERS

    Indexers are location indicators and are used to access class objects, just like accessing

    elements in an array. They are useful in cases where a class is a container for other objects.

    An Indexer looks like a property and is written the same way a property is written, but with

    two differences:

    1. The indexer takes an index argument and looks like an array.

    2.

    The indexer is declared using the name this.

    Ex:

    public double this [ int idx ]

    {

    get

    {

    //Return desired data

    }

    set

    {

    //Set desired data

    }

    }

    DIFFERENCES BETWEEN INDEXERS AND PROPERTY

    1. A property can be static member, whereas an indexer is always an instance member.

    2.

    A get accessor of a property corresponds to a method no parameters, whereas a get accessor of

    an indexer corresponds to a method with the same formal parameter list as the indexer.

    3. A set accessor of a property corresponds to a method with a single parameter named value,

    whereas a set accessor of an indexer corresponds to a method with the same formal parameter

    list as the indexer, plus the parameter named value.

    4.

    It is an error for an indexer to declare a local variable with same name as an indexer

    parameter.

    usingSystem;

    usingSystem.Collections ;

  • 8/10/2019 11-06-25-11-23-51-966-carun

    55/67

    classList

    {

    ArrayList array = newArrayList ();

    publicobjectthis[intindex]

    {

    get

    {

    if(index < 0 && index >=array.Count )

    {

    returnnull;

    }

    else

    {

    return(array[index]);}

    }

    set

    {

    array[index] = value;

    }

    }

    }

    classIndexerTest

    {

    publicstaticvoidMain()

    {

    List list = newList ();

    list [0] = "123";

    list [1] = "abc";

    list [2] = "xyz";

    for(inti = 0; i

  • 8/10/2019 11-06-25-11-23-51-966-carun

    56/67

    Errors are mistakes that can make a program go wrong. An error may produce an incorrect

    output or may terminate the execution of the program abruptly or even may cause the system to crash.

    TYPES OF ERROR

    1.

    Compile Time Error

    2.

    Run Time Error

    Compile Time Errors

    1. Missing Semicolon.

    2. Missing brackets in classes and methods

    3.

    Misspelling of identifiers and keywords

    4.

    Use of = in place of == operator, etc.

    Run Time Errors

    1. Dividing an integer by zero

    2.

    Accessing an element that is out of the bounds of an array3.

    Converting an invalid string to a number or vice versa.

    4. Attempting to use a negative size for an array.

    usingSystem;

    classException

    {

    publicstaticvoidMain()

    {

    inta = 10;

    intb = 5;

    intc = 5;

    intx = a / (b - c);

    Console.WriteLine ("X = " + x);

    inty = a / (b + c);

    Console.WriteLine ("Y = " + x);

    }

    }

    EXCEPTION

    An Exception is a condition that is caused by a run-time error in the program.

    If the exception object is not caught and handled properly, the compiler will display an error

    message and will terminate the program If we want the program to continue with the execution of the

    remaining code, then we should try to catch the exception object thrown by the error condition and

  • 8/10/2019 11-06-25-11-23-51-966-carun

    57/67

    then display an appropriate message for taking corrective actions. This task is known as exception

    handling.

    EXCEPTION HANDLING MECHANISM

    1.

    Find the problem (Hitthe exception)

    2.

    Inform that an error has occurred (Throwthe exception)

    3.

    Receive the error information (Catchthe exception)

    4. Take corrective actions ( Handlethe exception)

    Throw Point

    Exceptions are thrown by methods that are invoked from within the try blocks. The point at

    which an exception is thrown is called the throw point. Once an exception is thrown to the catch block,

    control cannot return to the throw point.

    SYNTAX OF EXCEPTION HANDLING CODE

    ------------

    ------------

    try

    {

    Statement; //generates an exception

    }

    catch(Exception e)

    {

    Statement; //process the exception

    tryBlock

    Statement that

    caused an

    exception

    catchBlock

    Statements thathandle the

    exception

    Throws

    Exception

    Exception object

    creator

    Exceptionhandler

  • 8/10/2019 11-06-25-11-23-51-966-carun

    58/67

    }

    USING TRY AND CATCH FOR EXCEPTION HANDLING

    usingSystem;

    classEx

    {

    publicstaticvoidMain()

    {

    inta = 10;

    intb = 5;

    intc = 5;

    try

    {

    intx = a / (b - c);Console.WriteLine ("X = " + x);

    }

    catch(Exception e)

    {

    Console.WriteLine ("Division by Zero");

    }

    inty = a / (b + c);

    Console.WriteLine ("Y = " + y);

    }

    }

    MULTIPLE CATCH STATEMENTS

    Syntax:

    try

    {

    Statement; // generates an exception

    }

    catch(Exception Type 1 e)

    {

    Statement; // processes exception type 1

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    59/67

    catch(Exception Type 2 e)

    {

    Statement; // processes exception type 2

    }

    .

    catch(Exception Type N e)

    {

    Statement; // processes exception type N

    }

    Note:

    C# does not require any processing of the exception at all. We can simply have a catch

    statement with an empty block to avoid program abortion.

    Ex:

    catch (Exception e){

    }

    USING MULTIPLE CATCH BLOCKS

    usingSystem;

    classMultiple

    {

    publicstaticvoidMain()

    {

    int[] a = {5,10};

    intb = 5;

    try

    {

    intx = a[2] / b - a[1];

    }

    catch(ArithmeticException e)

    {

    Console.WriteLine ("Division By Zero");

    }

    catch(IndexOutOfRangeException e)

    {

    Console.WriteLine ("Array index error");

    }

    catch(ArrayTypeMismatchException e)

  • 8/10/2019 11-06-25-11-23-51-966-carun

    60/67

    {

    Console.WriteLine ("Wrong data type");

    }

    inty = a[1] / a[0];

    Console.WriteLine ("Y =" + y);

    }

    }

    THE EXCEPTION HIERARCHY

    CASE ONE

    try

    {

    ----------

    ---------- //Throw divide by Zero Exception}

    catch(Exception e)

    {

    ------------------

    }

    catch(DivideByZeroException e)

    {

    ---------------

    }

    CASE TWO

    try

    {

    ----------

    ---------- //Throw divide by Zero Exception

    }

    catch(DivideByZeroException e)

    {

    ---------------

    }

    catch(Exception e)

    {

    ------------------

  • 8/10/2019 11-06-25-11-23-51-966-carun

    61/67

    }

    GENERAL CATCH HANDLER

    A catch block which will catch any exception is called a general catch handler. A general catch

    handler does not specify any parameter and can be written as:

    try

    {

    -------------- // causes an exception

    }

    catch // no parameters

    {

    -------------

    ------------- // handles error

    }

    USING FINALLY STATEMENT

    C# supports another statement known as a finally statement that can be used to handle an

    exception that is not caught by any of the previous catch statements. A finally block can be used to

    handle any exception generated within a try block. It may be added immediately after the try block or

    after the last catch

    try try

    { {

    --------- ---------

    --------- ---------

    } }

    finally

    catch ( ----- )

    { {

    --------- --------

    --------- --------

    } }

    catch (------)

    {

    -------

    -------

    }

    finally

  • 8/10/2019 11-06-25-11-23-51-966-carun

    62/67

    {

    -----

    }

    EXECUTION PATHS OF TRY CATCH FINALLY BLOCKS

    NESTED TRY BLOCKS

    try

    {

    ---------- (Point 1)

    try

    {

    --------- (Point 2)

    }

    catch

    {-------- (Point 3)

    }

    finally

    {

    --------

    }

    ------------------ (Point 4)

    }

    catch

    {

    ------------

    }

    finally

    {

    ------------

    ------------

    }

    When nested try blocks are executed, the exceptions that are thrown at various points are handled as

    follows:

    1.

    The Points P1 and P4 are outside the inner try block and therefore any exceptions thrown at

    these points will be handled by the catch in the outer block. The inner block is simply ignored.

  • 8/10/2019 11-06-25-11-23-51-966-carun

    63/67

    2. Any exception thrown at point P2 will be handled by the inner catch handler and the inner

    finally will be executed. The execution will continue at point P4 in the program.

    3.

    If there is not suitable catch handler to catch an exception thrown at P2, the control will leave

    the inner block (after executing the inner finally) and look after a suitable catch handler in the

    outer block. If a suitable one is found, then that handler is executed followed by the outer

    finally code. Remember, the code at Point 4 will be skipped.

    4.

    If an exception is thrown at point P3, it is treated as if it had been thrown by the outer try

    block and, therefore, the control will immediately leave the inner block (after executing the

    inner finally) and search for a suitable catch handler in the outer block.

    5.

    In case, a suitable catch handler is not found, then the system will terminate program

    execution with an appropriate message.

    IMPLEMENTING NESTED TRY BLOCKS

    usingSystem;classNestedTry

    {

    staticintm = 10;

    staticintn = 0;

    staticvoidDivision()

    {

    try

    { intk = m / n; }

    catch(ArgumentException e)

    { Console.WriteLine ("Caught an Exception"); }

    finally

    { Console.WriteLine ("Inside Division Method"); }

    }

    publicstaticvoidMain()

    {

    try

    {

    Division ();

    }

    catch(DivideByZeroException e)

    {

    Console.WriteLine ("Caught an Exception");

    }

  • 8/10/2019 11-06-25-11-23-51-966-carun

    64/67

    finally

    {

    Console.WriteLine ("Inside Main Method");

    }

    }}

    THROWING OUR OWN EXCEPTIONS

    There may be times when we would like to throw our own exceptions. We can do this by using

    the keyword throw as follows:

    thrownew Throwoble_subclass

    Ex:

    throw new ArithmeticException ( );

    throw new FormatException ( );

    usingSystem;

    classMyException:Exception

    {

    publicMyException(stringmessage)

    {

    }

    }

    classTestMyException

    {

    publicstaticvoidMain()

    {

    int x = 5, y = 1000;

    try

    {

    floatz = (float) x / (float) y;

    if(z

  • 8/10/2019 11-06-25-11-23-51-966-carun

    65/67

    Console.WriteLine (e.Message );

    }

    finally

    {

    Console.WriteLine ("I am always here");

    }

    }

    }

    CHECKED AND UNCHECKED OPERATORS

    usingSystem;

    classCheck

    {

    publicstaticvoidMain(){

    inta = 200000;

    intb = 300000;

    try

    {

    intm = checked(a * b);

    }

    catch(OverflowException e)

    {

    Console.WriteLine (e.Message );

    }

    }

    }

    Summary

    This chapter took a close look at the rich mechanism C# has for dealing with error conditions

    through exceptions. You are not limited to the generic error codes that could be output from your

    code, but you have the ability to go in and uniquely handle the most granular of error conditions.

    Sometimes these error conditions are provided to you through the .NET Framework itself, but at other

    times, you might want to go in and code your own error conditions as was shown here in this chapter.

    In either case, you have a lot of ways of protecting the workflow of your applications from unnecessary

    and dangerous faults.

  • 8/10/2019 11-06-25-11-23-51-966-carun

    66/67

    Objective

    1. Boxing in .Net allows the user to converta) a interger type to double b) a reference type to a value typec) a value type to a reference type d) a double type to interger

    2. The RangeValidator control supports the following data typesa) Integer only b) Date, Integer and String C) only string d) Date and Integer

    3. How to kill a user session explicitly?a) Session.Close() b) Session.Discard() c) Session.kill() d) Session.Abandon()

    4. Convert vs. Parse methodsa) Convert allows null values, Parse cannot b) Convert converts the value, Parse is forparsingc) Both are same d) None of these

    5. Different ways a method can be overloaded in C#.NETa) Different parameter data types b) Different number of parameters

    c) Different order of parameters d) All of above

    6. Can you store multiple data types in System.Array?a) No b) Yes

    7. Which of the following is incorrect about System.Text.StringBuilder and System.String?a) StringBuilder is more efficient when there is a large amount of string manipulationb) Strings are immutable, so each time a string is changed, a new instance in memory is created.c) StringBuilder is mutable; when you modify an instance of the StringBuilder class, you modify theactual string, not a copyd) Strings are mutable in .Net

    8. What is accessibility modifier protected internal?

    a) It is available to classes that are within the same assembly and derived from the specified baseclass.b) It is available within the class definitionc) It is the most permissive access leveld) It is the least permissive access level

    9. What is the .NET collection class that allows an element to be accessed using a unique key?a) HashTable b) ArrayList c) SortedList

    10. Can you inherit multiple interfaces?a) Yes b) No

    11. What does the keyword virtual mean in the method definition?

    a) The method is public b) The method can be derivedc) The method is static d) The method can be over-ridden

  • 8/10/2019 11-06-25-11-23-51-966-carun

    67/67

    PART A

    1.

    What is encapsulation? How it is achieved?

    2. What is method overloading?

    3.

    What is polymorphism? How it is achieved?

    4.

    What do you mean by abstract methods and classes?

    5. What is inheritance?

    6. What is garbage collection?

    7.

    What is exception? How it is handled in C#?

    8.

    What are the various types of Exceptions?

    9. What is the use of finally block?

    10.What is interface? How it is defined in C#?

    11.

    How to compare two objects in C#?

    12.

    How to create Cloneable objects?

    13.

    What is delegate? How it is created in C#?

    14.What do you mean by event?

    15.What is the use of indexer? Write the syntax for indexer?

    16.

    Define properties. Explain the syntax for properties.

    17.What do you mean by operator overloading?

    18.Explain the syntax for unary and binary operator overloading.

    PART B

    1. Explain about interfaces in C#.

    2.

    Explain in detail about Exception Handling.

    3.

    Briefly explain the concept of Delegates.

    4. What is event? How events are created? Give example.

    5. Explain in detail about Inheritance?

    6. Explain in detail about the concept of operator overloading.