2 Object Oriented Programming And Events

NET Centric Computing · Unit 2

Object-Oriented Programming and Events

Exam-focused notes for Object-Oriented Programming and Events (NET Centric Computing, BIT351): what the TU syllabus asks and how it has actually been tested, with 2 solved past questions from this unit.

Object-Oriented Programming and Events in short

This chapter covers how C# objects send notifications through delegates and events, and how a program deals with run time errors. Good error handling keeps an application from crashing and gives users clear messages.

Object-Oriented Programming and Events: notes

Delegates and event handling

A delegate is a type that holds a reference to a method. It is like a function pointer, but type safe. The delegate and the method must have the same return type and parameters.

public delegate int Operation(int a, int b);

static int Add(int a, int b) => a + b;

Operation op = Add;
Console.WriteLine(op(3, 4));    // 7

A delegate can point to many methods at once. This is called a multicast delegate, and the methods are added with +=. Built in delegate types are Action (no return value), Func (returns a value) and Predicate (returns bool).

An event is a member that lets a class (the publisher) tell other classes (the subscribers) that something happened. An event is based on a delegate. Only the publisher can raise it. Subscribers can only add or remove handlers with += and -=.

Role of delegates in event handling:

  • The delegate defines the signature that every handler must follow.
  • It stores the list of handler methods.
  • When the event is raised, the delegate calls every handler in turn.
public class Button
{
    public event EventHandler Clicked;           // event based on a delegate

    public void Click()
    {
        Clicked?.Invoke(this, EventArgs.Empty);  // raise the event
    }
}

public class Program
{
    static void OnClicked(object sender, EventArgs e)
        => Console.WriteLine("Button was clicked");

    static void Main()
    {
        var b = new Button();
        b.Clicked += OnClicked;                  // subscribe
        b.Click();                               // prints the message
    }
}

The standard pattern uses EventHandler or EventHandler<TEventArgs>. The first parameter is the sender object. The second carries the event data.

What this unit covers

  • Delegates and event handling
  • Exception handling and error management
  • Throwing and catching exceptions
  • Input validation with exceptions

Throwing and catching exceptions

2081.1 · 10 marks

Differentiate between error and exception. Write a program to take the input for any five subjects and throw the exception if the given marks is negative or exceed 100.[10]

Show solved answer

Errors and exceptions, and validating five subject marks

How the two differ

In everyday use an error is any fault in a program, but as a technical term the two words describe faults of very different severity, and the .NET framework treats them differently from Java.

In .NET there is no separate Error base class. Everything that can be thrown derives from System.Exception. The distinction that matters is between the ordinary exceptions an application is expected to anticipate and recover from, such as FormatException, IOException or SqlException, and the fatal conditions raised by the runtime itself, such as OutOfMemoryException, StackOverflowException and AccessViolationException. The second group corresponds to what Java calls an Error, and .NET makes the point sharply: since .NET 2.0 a StackOverflowException cannot be caught at all, the process is simply terminated, because once the stack is gone there is no reliable way to keep running. The word error is also used for a compile time error, which the compiler refuses to build, and for an ordinary failure that a method reports through a return value or a status code rather than by throwing.

BasisError (fatal condition)Exception (handled condition)
MeaningThe environment can no longer run the program correctlyAn abnormal but foreseeable situation in the application
Raised byThe CLR or the operating systemThe application, a library, or the CLR for bad arguments
Typical examplesOutOfMemoryException, StackOverflowException, AccessViolationExceptionFormatException, DivideByZeroException, FileNotFoundException, a custom InvalidMarksException
RecoverableNormally not; a stack overflow cannot even be caughtYes, that is the point of catching it
Right responseLet the process fail and log it outside the processtry, catch, finally, or a using block
In JavaA separate java.lang.Error hierarchyThe java.lang.Exception hierarchy

The practical consequence is that a program should catch the exception types it can actually do something about. Writing catch (Exception) around everything hides genuine defects such as a null reference, and it cannot rescue the fatal conditions anyway, so it buys nothing and costs a great deal in lost diagnostics.

Within the exception family, .NET also distinguishes exceptions by who is at fault. ArgumentException, ArgumentNullException and InvalidOperationException say the calling code used the API wrongly and should be fixed rather than caught, whereas IOException or a timeout describes the outside world misbehaving, which the caller must genuinely handle. A custom type for a business rule, like the marks rule below, belongs to that second group.

A C# program that validates five subject marks

The program reads marks for five subjects, and a method throws a custom exception when a value is negative or greater than 100. Each subject is validated inside its own try block so that one bad value does not stop the remaining subjects from being checked.

using System;

// A custom exception carries the offending data as well as the message.
public class InvalidMarksException : Exception
{
    public string Subject { get; }
    public int Marks { get; }

    public InvalidMarksException(string subject, int marks, string message)
        : base(message)
    {
        Subject = subject;
        Marks = marks;
    }
}

public static class Program
{
    private static readonly string[] Subjects =
        { "Mathematics", "Physics", "Chemistry", "English", "Computer" };

    private static void ValidateMarks(string subject, int marks)
    {
        if (marks < 0)
        {
            throw new InvalidMarksException(subject, marks,
                subject + ": " + marks + " is negative, marks cannot fall below 0.");
        }

        if (marks > 100)
        {
            throw new InvalidMarksException(subject, marks,
                subject + ": " + marks + " is too high, marks cannot exceed 100.");
        }
    }

    public static void Main()
    {
        int[] marks = new int[Subjects.Length];

        Console.WriteLine("Enter the marks obtained in five subjects.");

        for (int i = 0; i < Subjects.Length; i++)
        {
            Console.Write(Subjects[i] + " (0 to 100): ");
            string typed = Console.ReadLine();

            // Console input is untrusted text, so it is parsed rather than assumed numeric.
            // TryParse reports failure through its return value instead of throwing.
            while (!int.TryParse(typed, out marks[i]))
            {
                Console.Write("Please type a whole number for " + Subjects[i] + ": ");
                typed = Console.ReadLine();
            }
        }

        int total = 0;
        int accepted = 0;

        Console.WriteLine();
        Console.WriteLine("Checking the marks.");

        for (int i = 0; i < Subjects.Length; i++)
        {
            try
            {
                ValidateMarks(Subjects[i], marks[i]);

                Console.WriteLine(Subjects[i] + ": " + marks[i] + " is valid.");
                total += marks[i];
                accepted++;
            }
            catch (InvalidMarksException ex)
            {
                // Only the exception this code knows how to handle is caught.
                Console.WriteLine("Invalid entry. " + ex.Message);
            }
        }

        Console.WriteLine();
        Console.WriteLine(accepted + " of 5 subjects accepted, total " + total + " marks.");
    }
}

A sample run:

Enter the marks obtained in five subjects.
Mathematics (0 to 100): 85
Physics (0 to 100): -10
Chemistry (0 to 100): 110
English (0 to 100): 75
Computer (0 to 100): 90

Checking the marks.
Mathematics: 85 is valid.
Invalid entry. Physics: -10 is negative, marks cannot fall below 0.
Invalid entry. Chemistry: 110 is too high, marks cannot exceed 100.
English: 75 is valid.
Computer: 90 is valid.

3 of 5 subjects accepted, total 250 marks.

Two details are worth defending in the viva. int.TryParse is used instead of int.Parse because a typing mistake is expected input and not an exceptional condition, so it is cheaper and clearer to test the return value than to throw and catch a FormatException. The custom InvalidMarksException derives from Exception and adds the subject and the marks as properties, so the handler can report precisely which entry failed rather than parsing the message text. If the same validation were reached from an ASP.NET Core page instead of the console, the message would be surfaced through model validation and rendered with Razor, which HTML encodes the value so that whatever the user typed cannot be treated as markup.

Open this answer on its own page →

Delegates and event handling

0 · 10 marks

Describe the roles of delegates in event handling. Illustrate the use of partial class with an example.[10]

--- A delegate is a type-safe function pointer in C that holds a reference to a method (or multiple methods) with a matching signature. It acts as an intermediary between the event source (publisher) and the event handler (subscriber). Syntax: --- Event handling in C follows the Publisher-Subscri...

Open this answer on its own page →