Practical 9: Streams and Delegates

CAB201 - Programming Principles

School of Computer Science, Faculty of Science

Agenda

Two distinct topics:

  1. I/O in C#: Input/Output to files
    • Reading and writing data to and from files
    • Working with directories
    • Using StreamReader and StreamWriter
  2. Delegates: OOP meets functional programming
    • Defining and using delegates
    • Higher-order methods
    • Lambda expressions
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

I/O in C#

I/O stands for Input/Output. It refers to the process of reading data from and writing data to external sources, such as files, network connections, and other devices.

The System.IO namespace in C# provides classes for reading and writing data to and from files.

We will mostly work with files and directories in CAB201.

CAB201 - Programming Principles
School of Computer Science, Faculty of Science

The File class

The File class in the System.IO namespace provides static methods for creating, copying, deleting, moving, and opening files.

For example, the File.Exists method checks if a file exists at a specified path, and the different File.Get* methods return information about a file.

string path = "C:\Users\Public\Documents\MyFile.txt";
if (File.Exists(path)) {
    Console.WriteLine(File.GetCreationTime(path));
    Console.WriteLine(File.GetLastWriteTime(path));
    Console.WriteLine(File.GetLastAccessTime(path));
    File.Delete(path);
}
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

The Directory class

Similarly, the Directory class in the System.IO namespace provides static methods for creating, moving, and deleting directories.

string path = "C:\Users\Public\Documents\MyDirectory";
if (Directory.Exists(path)) {
    Console.WriteLine(Directory.GetCreationTime(path));
    Console.WriteLine(Directory.GetLastWriteTime(path));
    Console.WriteLine(Directory.GetLastAccessTime(path));
    Directory.Delete(path);
}

Note that the Directory class is used to work with directories, while the File class is used to work with files.

CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Reading from a File with StreamReader

A stream is a sequence of bytes that can be read from or written to. Streams are used to read and write data from and to files, network connections, and other sources.

static void DisplayFile() {
    string path = "C:\Users\Public\Documents\MyFile.txt";
    if (!File.Exists(path)) return;
    using (StreamReader reader = new StreamReader(path)) {
        string line;
        while (true) {
            line = reader.ReadLine();
            if (line == null) break;
            Console.WriteLine(line);
        }
    }
}
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Writing to a File with StreamWriter

To write data to a file, you can use the StreamWriter class.

static void WriteToFile() {
    string path = "C:\Users\Public\Documents\MyFile.txt";
    using (StreamWriter writer = new StreamWriter(path)) {
        writer.WriteLine("Hello, world!");
    }
}
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Delegates

A delegate is like an interface for methods. It defines a method signature that can be used to reference any method that matches the signature.

delegate int BinaryOperation(int a, int b);
public static int Add(int first, int second) {
    return first + second;
}
BinaryOperation operation = Add;
Console.WriteLine(operation(5, 3)); // Output: 8

You may imagine operation as a variable that can be passed around and used to call the Add method.

CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Higher-Order Methods

Delegates can be used to create higher-order methods. These are methods that take other methods as arguments.

delegate int Transformer(int value);
public static int[] Apply(int[] values, Transformer transformer) {
    int[] result = new int[values.Length];
    for (int i = 0; i < values.Length; i++) {
        result[i] = transformer(values[i]);
    }
    return result;
}
Transformer square = value => value * value;
int[] values = { 1, 2, 3, 4, 5 };
int[] squared = Apply(values, square); // [1, 4, 9, 16, 25]
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Lambda Expressions

Lambda expressions are a shorthand way of defining methods using the => operator.

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

They are not delegates themselves, but being a method, they can be assigned to a delegate.

BinaryOperation add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // Output: 8
CAB201 - Programming Principles
School of Computer Science, Faculty of Science