π Lecture 1 β Visual Programming
π Overview: This introductory lecture sets the foundation for understanding visual programming as an event-driven paradigm applied to desktop, web, and mobile applications. It demonstrates the shift from traditional sequential programming to a model where programs react to events, using simple C++ examples to illustrate the core concepts.
ποΈ Topics Covered
This lecture introduces the course scope focusing on graphical user interfaces and event-driven programming across desktop, web, and mobile platforms. It presents two books as primary references: "Event processing in action" and "Windows presentation foundation unleashed". The lecture demonstrates the evolution from basic sequential input/output programs to event-reactive programs using keyboard input and file-change detection as event sources.
π Lecture Summary
Introduction to Visual Programming
This course focuses on graphical user interfaces and the event-driven model applied to desktop, web, and mobile applications. The prerequisites are C++ programming and data structures. The course takes a hands-on approach with in-class examples and programming assignments.
The primary textbooks are:
- "Event processing in action" by Opher Etzion and Peter Niblett
- "Windows presentation foundation unleashed" by Adam Nathan
The course covers event-driven programming in the browser using AJAX techniques and mobile event-driven programming, with no prerequisites for these topics.
π‘ Why this matters: Visual programming is fundamentally different from traditional sequential programming - instead of the program controlling the flow, user actions and system events drive the program's behavior.
First Example - Basic Input/Output
The first example demonstrates a simple sequential program that reads keyboard input and echoes it:
#include <iostream>
using namespace std;
int main() {
char a;
do {
a = cin.get();
cout << a;
} while (a != 'x');
return 0;
}
π Definition β Sequential programming: A programming model where the program executes instructions one after another in a predetermined order, with no external interruptions.
π Formula: cin.get() β Reads a single character from keyboard input
π Example: When you run ./example1 and type "hello", the program outputs "hello" immediately. Typing 'x' terminates the program.
Second Example - File Monitoring
The second example adds file monitoring capability, creating a busy wait loop:
#include <iostream>
#include <fstream>
int main() {
char a = '-';
do {
std::ifstream f("test.txt", std::ifstream::in);
if (f.good() && a != f.peek()) {
a = f.get();
std::cout << a << std::endl;
}
f.close();
} while (a != 'x');
return 0;
}
π Definition β Busy wait: A programming technique where the program continuously checks for a condition in a tight loop, consuming CPU resources even when no events are occurring.
π Example: This program constantly opens and reads "test.txt" file checking for changes, wasting CPU cycles if nothing changes. If you manually edit the file and add 'x', the program terminates.
Third Example - Multiple Event Sources
This example combines both keyboard and file monitoring using a hypothetical iskeyboardpressed() function:
#include <iostream>
#include <fstream>
int main() {
char a = '-', b;
do {
if (iskeyboardpressed()) {
b = std::cin.get();
std::cout << b << std::endl;
}
std::ifstream f("test.txt", std::ifstream::in);
if (f.good() && a != f.peek()) {
a = f.get();
std::cout << a << std::endl;
}
f.close();
} while (a != 'x' && b != 'x');
return 0;
}
π Definition β Event source: An entity that can generate events that the program can respond to, such as keyboard input or file system changes.
π Example: Now the program responds to TWO different events - keyboard presses AND file changes. If you type 'x' OR if the file contains 'x', the program terminates.
Refactored Version - Cleaner Event Handling
The improved version demonstrates event-driven programming principles with separated event handlers:
#include <iostream>
#include <fstream>
int onkeypress() {
char b = std::cin.get();
std::cout << b << std::endl;
return b == 'x';
}
int onfilechanged() {
char a = f.get();
std::cout << a << std::endl;
return a == 'x';
}
int main() {
char a = '-', b;
do {
if (iskeyboardpressed()) {
if (onkeypress())
return 0;
}
std::ifstream f("test.txt", std::ifstream::in);
if (f.good() && a != f.peek()) {
if (onfilechanged())
return 0;
}
f.close();
} while (true);
return 0;
}
π Definition β Event-driven programming: A programming paradigm where the program's flow is determined by events - actions such as user inputs, sensor outputs, or messages from other programs.
π Example: Each event (keypress or file change) has its own handler function. The program is more organized, focused, and scales better to handle many different event types.
β Key Takeaways
The core transformation from sequential to event-driven programming requires understanding that programs must be designed to react to multiple, potentially simultaneous events rather than following a predetermined path. The refactored approach demonstrates better code organization and scalability but introduces blocking as a significant challenge. The lecture establishes that event-driven programming, while initially more complex, scales effectively to handle large numbers of event sources in GUI applications. The key distinction is between programs that actively wait (busy wait) and those that efficiently respond to events as they occur.
π§ Quick Revision Questions
- What is the fundamental difference between sequential programming and event-driven programming?
- Why is busy waiting inefficient in event-driven programs?
- What are the two primary textbooks used in this course and what topics do they cover?
- How does the refactored version of the program improve upon the initial multiple-event-source version?
- What platforms does this course cover for event-driven programming applications?
π Lecture 2 β Event Driven Design
π Overview: This lecture builds on the introduction to event-driven design by exploring the concept of events in-depth, including their definition, types, and processing. It explains why event-based programming is crucial for visual programming and real-world applications, using analogies and a detailed flower delivery example to illustrate event-driven architecture.
ποΈ Topics Covered
The lecture covers the definition of an event in computing, the distinction between synchronous and asynchronous behavior, the nature of event processing and event-based programming, the benefits of event-driven design, types of events in non-real-time applications, and concludes with a comprehensive flower delivery example that demonstrates how events drive a real-world system.
π Lecture Summary
Event Refactoring and Definition
The lecture begins by refactoring the previous example to demonstrate how event detection can be modularized into separate functions like onkeypress() and onfilechanged(). An event is an occurrence within a particular system or domain, with two meanings: something that happened and the corresponding detection in the computer world. An event captures "some" things from the actual occurrence, and multiple events may capture "one" occurrence. Probabilistic events may or may not relate to an actual occurrence, such as a fraud detection event on a banking transaction. Every event is represented by an event-object, which contains information describing the details of the particular event type, e.g., key press, file event.
π Definition β Event: An occurrence within a particular system or domain, represented by an event-object that captures information about the occurrence.
Synchronous and Asynchronous Behavior
Using a coffee shop analogy, the lecture explains two types of behavior. If an order is completed, coffee ready, and pastry heated before the next order, that is synchronous behavior. Asynchronous operations can be started, and we can do something else before they are completed. There are observed events and deduced events. A situation is an event occurrence that requires a reaction.
π Definition β Synchronous behavior: Operations are completed before the next operation can be started. π Definition β Asynchronous behavior: Operations can be started, and we can do something else before they are completed.
Events in Computing Systems
Examples of events in computing systems include interrupts and exceptions on a computer (e.g., Divide by zero), patient monitoring by sensors, car sensors alerting to oil or pressure situations, banking alerts, and road tolling. Event processing is computing that performs operations on events. Common event processing operations include reading, creating, transforming, and deleting events. The design, coding, and operation of applications that use events is called event-based programming or event-driven architecture.
π‘ Why this matters: Without event-driven programming, we would have to poll for events, which is inefficient. Waiting for a single event is a blocking operation.
Why Event-Based Applications
Event-based applications are easier to scale. They are well suited to visual programming where multiple GUI elements and many sources of events exist. Event-driven design has a direct mapping to the real world and is deterministic β there is an exact mapping between a situation in the real world and its representation in the event processing system. At the same time, it is approximate β the event processing system provides an approximation to real world events.
Types of Events in Non-Real Time Applications
Types of events include: Mouse and keyboard events, secondary events of GUI elements, file events, message-based parallel and local communication, and network events.
Flower Delivery Example
The lecture presents a flower delivery example from the book. A consortium of flower stores has established an agreement with local independent van drivers to deliver flowers. When a store gets a flower delivery order:
- It creates a request broadcast to relevant drivers within a certain distance.
- A driver is assigned.
- The customer is notified that a delivery has been scheduled.
- The driver makes the pickup and delivery.
- The person receiving the flowers confirms the delivery time by signing on the driver's mobile device.
The system maintains a ranking for each driver based on on-time delivery. Each store has a profile that can include a constraint on the driver's ranking. The profile also indicates whether the store wants automatic assignment or wants to choose from several applications. A permanently weak driver has fewer than five assignments on all days active. An idle driver has at least one day of activity with no assignments. A consistently weak driver has assignments, when active, that are at least two standard deviations lower than the average. A consistently strong driver has daily assignments at least two standard deviations higher than the average. An improving driver has assignments that increase or stay the same day by day.
π Definition β Permanently weak driver: A driver with fewer than five assignments on all the days on which the driver has been active. π Definition β Idle driver: A driver with at least one day of activity that had no assignments. π Definition β Consistently weak driver: A driver whose assignments, when active, are at least two standard deviations lower than the average assignments per driver on that day. π Definition β Consistently strong driver: A driver whose daily assignments are at least two standard deviations higher than the average number of assignments per driver on each day in question. π Definition β Improving driver: A driver whose assignments increase or stay the same day by day.
β Key Takeaways
Events are occurrences that are detected and represented by event-objects in computing. The distinction between synchronous and asynchronous behavior is critical for understanding how event-driven systems work. Event-based programming is preferred over polling because it is non-blocking, scalable, and provides a direct mapping to real-world situations. Event processing involves reading, creating, transforming, and deleting events. The flower delivery example demonstrates a complex, real-world event-driven system with multiple event sources (store orders, driver assignments, delivery confirmations) and rules (driver rankings, store profiles, performance classifications).
π§ Quick Revision Questions
- What is the difference between an event and an event-object?
- Give an example of a probabilistic event in a banking system.
- What is the difference between synchronous and asynchronous behavior?
- List four common event processing operations.
- In the flower delivery example, what defines a "consistently strong driver"?
π Lecture 3 β Event-Driven Architecture
π Overview: This lecture introduces event-driven architecture (EDA) as an alternative to request-response based applications. It explains the fundamental concepts of events, event producers and consumers, and how events decouple system components. The lecture also compares event-driven architecture with service-oriented architecture and provides practical definitions for different types of events and event processing.
ποΈ Topics Covered
The lecture begins by contrasting request-response and event-driven architectures, explaining how events are based on decoupling principles and are independent of producers and consumers. It then defines key concepts including event channels, event producers and consumers, raw and derived events, stateless event processing, and event streams. The lecture also covers types of event agents and event attributes, and provides a code example mapping event definitions to a C++ program. Finally, it discusses real-world examples of event producers and consumers in hardware, software, and human interaction contexts.
π Lecture Summary
Request-Response vs Event-Driven Architecture
Request-response based applications, like a web browser, send queries and updates using synchronous interactions. In contrast, events are based on the principle of decoupling. Events have already happened, whereas requests ask for something to happen. In request-response, the service requester (client) contacts the service provider (server). In event-driven architecture, the event producer sends events to the event consumer. A customer order can be represented as either an event or a request, each having different benefits.
An event has meaning independent of its producers and consumers, which is not the case for requests. Events are often one way (push events) and decouple producers from consumers. Events can be processed asynchronously, can have more than one consumer, each processing it differently, and may process a sequence of events over time. This reduces latency compared to the "pull" style of request-response.
π‘ Why this matters: Understanding the distinction between events and requests is fundamental to choosing the right architectural pattern for different system requirements, especially when decoupling and asynchronous processing are needed.
Event Channels and Architecture Comparison
An event channel is a subscription mechanism for events that further decouples consumers and producers. It can even be an intermediate XML file to store events. Event-driven architecture (EDA) is an architectural style where components execute in response to receiving event notifications. Service-oriented architecture (SOA) is built from request-response and moves away from monolithic applications. These architectures share many similarities, and a component can often provide both modes of contacting it.
π Definition β Event Channel: A subscription mechanism for events that further decouples consumers and producers.
Core Event Definitions
EVENT PRODUCER: An event producer is an entity at the edge of an event processing system that introduces events into the system.
EVENT CONSUMER: An event consumer is an entity at the edge of an event processing system that receives events from the system.
RAW EVENT: A raw event is an event that is introduced into an event processing system by an event producer.
DERIVED EVENT: A derived event is an event that is generated as a result of event processing that takes place inside an event processing system.
STATELESS EVENT PROCESSING: An event processing agent is said to be stateless if the way it processes one event does not influence the way it processes any subsequent events.
EVENT STREAM: An event stream (or stream) is a set of associated events. It is often a temporally totally ordered set (with a well-defined timestamp-based order to the events in the stream). A stream where all events must be of the same type is called a homogeneous event stream; a stream where events may be of different types is called a heterogeneous event stream.
Mapping Events to C++ Code
The lecture presents a C++ program and asks students to map event definitions to the code. The program demonstrates a file monitoring system that checks for keyboard input and file changes in a loop.
The program includes:
onkeypress()function that reads keyboard input (event consumer for keyboard events)onfileread()function that reads a file character by character and detects changesonfilechanged()function that outputs the changed character- A main loop that continuously checks for keyboard input and file changes
In this program:
- The keyboard and file system act as event producers
- The functions
onkeypress(),onfileread(), andonfilechanged()act as event consumers - The variable
filechangedserves as a simple event channel mechanism - The file content changes represent raw events
- The detection of a character change (
filechanged = 1) represents a derived event
Event Attributes and Types
An event type is a specification for a set of event objects that have the same semantic intent and same structure. Every event object is an instance of an event type. An event attribute is a component of the structure of an event, with each attribute having a name and a data type. Events can have attributes like occurrence/detection time, certainty, source, and location. Events can be composed, generalized, and specialized.
π Definition β Event Type: A specification for a set of event objects that have the same semantic intent and same structure.
π Definition β Event Attribute: A component of the structure of an event, where each attribute has a name and a data type.
Event producers can produce events that are:
- Hardware generated
- Software generated
- From human interaction
Event consumers have similar types. Examples include: locking or unlocking a door, raising or lowering a barrier, applying brakes on a vehicle, opening or closing a valve, controlling a railroad switch, and turning equipment on or off.
β Key Takeaways
Events are fundamentally different from requests because events have already happened and are independent of their producers and consumers, while requests ask for something to happen. The key benefit of event-driven architecture is decoupling, which allows for asynchronous processing, multiple consumers, and reduced latency compared to request-response. Students must understand the distinction between raw events (introduced by producers) and derived events (generated by internal processing), as well as stateless versus stateful event processing. Event channels further enhance decoupling by providing subscription mechanisms between producers and consumers. Finally, event attributes including occurrence time, certainty, source, and location are essential for understanding real-world event objects in software systems.
π§ Quick Revision Questions
- What are the three main differences between events and requests in software architecture?
- What is an event channel and what three purposes does it serve in event-driven architecture?
- Define and differentiate between raw events and derived events with an example for each.
- What does it mean for event processing to be stateless, and how does this differ from stateful processing?
- List four types of event attributes and give an example of how each might apply to a flower delivery event.
π Lecture 4 β Getting Introduced to C#
π Overview: This lecture introduces C# programming language, its history and relationship with .NET platform, and provides a comprehensive overview of C# features including type system, generics, preprocessor directives, and basic programming syntax. It covers how C# was developed as a clean-room implementation following Microsoftβs dispute with Sun over Java extensions, and demonstrates essential C# programming concepts through practical examples including console-based and GUI-based Hello World programs.
ποΈ Topics Covered
The lecture covers the historical context of C# development including the Java and J++ controversy, clean-room design concept, and the origin of C# name from βCoolβ (C-like Object Oriented Language). It then explains how to obtain and install Visual Studio, presents notable features of C# including type safety, garbage collection, and property syntax, discusses the Common Type System distinguishing value types and reference types, demonstrates boxing/unboxing and generics concepts, covers pre-processor directives and XML documentation, and concludes with practical Hello World examples in both console and GUI formats.
π Lecture Summary
Getting Introduced to C#
The lecture begins with the historical context of C# development. Microsoft wanted to extend Java to communicate with COM (Component Object Model), but Sun Microsystems opposed this as it would make Java platform dependent. Microsoft then pursued a clean-room implementation of Java.
π Definition β Clean-room design: The method of copying a design by reverse engineering and then recreating it without infringing any copyrights and trade secrets associated with the original design. It relies on independent invention but cannot circumvent patent restrictions.
The initial name for C# was βCoolβ, which stood for βC-like Object Oriented Languageβ. C# design most directly reflects .NET (CLR) design, but C# is a language while .NET is the platform.
To get started, download Visual Studio from http://www.microsoft.com/visualstudio, choose βVisual Studio Express 2012 for Windows Desktopβ, and install/register online. Create a new project by selecting File, New Project, Visual C#, Console Application.
Notable Features of C#
Key features include:
- No global variables or functions
- Locals cannot shadow global variables
- Strict boolean type exists
- Memory address pointers can only be used in specifically marked βunsafeβ blocks and require permissions
- No instruction to βfreeβ memory β only garbage collection
- Try-finally block is supported
- No βmultiple inheritanceβ but interfaces are supported
- Operator overloading is allowed
- More type-safe (only integer widening allowed)
- Enumeration members are scoped
- Property syntax for getters and setters
- No checked exceptions
- Functional programming features like function objects and lambda expressions
π‘ Why this matters: These features make C# a modern, type-safe, and memory-managed language that differs significantly from C++ in its approach to memory management and type safety.
Common Type System: Value Types vs Reference Types
The Common Type System of C# has value types and reference types.
Value types (int, float, char, System.DateTime, enum, struct):
- Instances do not have referential identity nor referential comparison semantics
- Derived from System.ValueType
- Can always be created, copied, and have a default value
Reference types (Object, System.String, System.Array):
- Have the notion of referential identity
- Default equality and inequality comparisons test for referential rather than structural equality unless overloaded (e.g., System.String)
- Not βalwaysβ possible to create an instance, copy an existing instance, or perform a value comparison on two instances, though specific types can provide such services by exposing a public constructor or implementing a corresponding interface
Boxing and Unboxing
Boxing stores a value type in a reference type.
π Example:
int foo = 42; // Value type
Object bar = foo; // foo is boxed to bar
int foo2 = (int)bar; // Unboxed back to value type
Generics in C#
Generics are like templates in C++. They allow type-safe data structures without committing to actual data types.
π Example:
public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
GenericList<int> list1 = new GenericList<int>();
GenericList<string> list2 = new GenericList<string>();
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}
Pre-processor Directives and Comments
Pre-processor directives like #if, #else, #endif, #region, #endregion are supported. Comments are written using // for single-line and /* */ for multi-line comments.
XML Documentation System
C# provides an XML documentation system for documenting code.
π Example:
public class Foo {
/** <summary>A summary of the method.</summary>
* <param name="firstparam">A description of the parameter.</param>
* <remarks>Remarks about the method.</remarks> */
public static void Bar(int firstparam) {}
}
Hello World Examples
Console-based Hello World:
using System;
class Program {
static void Main() {
Console.WriteLine("Hello world!");
}
}
The using System; clause uses System as a candidate prefix for types used in the source code. Console is a static class in the System namespace.
To prevent the console window from disappearing quickly in Visual Studio, add Console.ReadLine(); at the end.
GUI-based Hello World:
using System.Windows.Forms;
class Program
{
static void Main()
{
MessageBox.Show("Hello world!");
}
}
Interactive Hello World with input:
using System;
class InteractiveWelcome
{
public static void Main()
{
Console.Write("What is your name?: ");
Console.Write("Hello, {0}! ", Console.ReadLine());
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}
β Key Takeaways
C# was developed as Microsoft's clean-room implementation after their dispute with Sun over Java extensions, with its original name being "Cool". The language features a strict type system with value types (derived from System.ValueType) and reference types, where value types always have default values and can be copied while reference types focus on referential identity. C# eliminates manual memory management by relying entirely on garbage collection, supports generics similar to C++ templates, and enforces type safety with no global variables or functions. The using directive simplifies coding by allowing namespace prefixes instead of full type names, and the Console class provides methods like WriteLine(), Write(), and ReadLine() for console I/O operations.
π§ Quick Revision Questions
- What was the original name of C# and what did it stand for?
- What is the key difference between value types and reference types in C#?
- How does boxing work in C# and why would you use it?
- What is the purpose of the
using System;directive in C# programs? - Why does C# not allow a "free" instruction for memory, and what does it use instead?
π Lecture 5 β Chapter 5
π Overview: This lecture introduces fundamental C# data types including booleans, integers, floating-point numbers, and strings. It covers arrays (single-dimensional, jagged, and multi-dimensional), control flow statements (if/else, switch), all four loop types (while, do-while, for, foreach), and method declaration with parameter passing mechanisms. These concepts form the building blocks for writing structured C# programs.
ποΈ Topics Covered
Boolean types with examples, integer types in C#, floating-point and decimal types, System.String escape sequences and verbatim character, operators supported by C#, single-dimensional arrays, jagged arrays (array of arrays), multi-dimensional arrays, if-else control statements, switch statement with branching, while loops, for loops with break/continue, foreach loops, method declaration using attributes-modifiers-return-type-name-parameters syntax, parameter passing with ref, out, and params keywords, the "this" pointer, and the dot operator for accessing members.
π Lecture Summary
Boolean Types
Boolean types represent true/false values in C#. The bool keyword is used to declare boolean variables. In the example, bool content = true; and bool nocontent = false; are used with Console.WriteLine() to output boolean values. The format string {0} acts as a placeholder for the boolean value.
π Definition β Boolean: A data type that can hold only two values: true or false.
π Syntax: bool variableName = true/false; β declares and initializes a boolean variable
π Example:
bool content = true;
bool nocontent = false;
Console.WriteLine("It is {0} that C# Station provides content.", content);
// Output: It is True that C# Station provides content.
Integer Types in C#
C# provides a range of integer types with different sizes and storage capacities. These include sbyte, byte, short, ushort, int, uint, long, and ulong. Each type has specific minimum and maximum values based on its bit size.
Floating Point and Decimal Types
C# offers floating-point types (float, double) and the decimal type for precise monetary calculations. float is 32-bit, double is 64-bit, and decimal is 128-bit with higher precision for financial applications.
System.String Escape Sequences
The System.String type supports escape sequences using the backslash \ character. Common escape sequences include \n (new line), \t (tab), and \\ (backslash). The verbatim character @ allows strings to be written exactly as typed, ignoring escape sequences.
π Definition β Verbatim Character (@): A character that tells the compiler to treat the string literally, ignoring all escape sequences.
π Example: @"C:\Program Files" outputs C:\Program Files without interpreting \P as an escape sequence.
Operators in C#
C# supports a comprehensive set of operators including arithmetic (+, -, *, /, %), relational (<, >, ==, !=, <=, >=), logical (&&, ||, !), assignment (=, +=, -=), and bitwise operators.
Arrays in C#
Arrays in C# can be single-dimensional, jagged (array of arrays), or multi-dimensional. Arrays use a zero-based index and their size must be an integer type value.
Single-dimensional arrays: Declared as int[] myints = { 5, 10, 15 };
Jagged arrays: Array of arrays, declared as bool[][] mybools = new bool[2][]; where each inner array can have different sizes.
Multi-dimensional arrays: Declared as double[,] mydoubles = new double[2, 2]; with fixed dimensions.
π Definition β Jagged Array: An array whose elements are themselves arrays, where each sub-array can have a different size.
π Example:
int[] myints = { 5, 10, 15 };
bool[][] mybools = new bool[2][];
mybools[0] = new bool[2];
mybools[1] = new bool[1];
double[,] mydoubles = new double[2, 2];
mydoubles[0, 0] = 3.147;
Console.WriteLine("mydoubles[0, 0]: {0}", mydoubles[0, 0]);
// Output: mydoubles[0, 0]: 3.147
π‘ Why this matters: Understanding jagged versus multi-dimensional arrays is crucial for memory-efficient data structures where rows have varying lengths.
Control Statements: if/else
The if-else statement works similarly to C++. It evaluates boolean expressions and executes corresponding code blocks. Logical operators || (OR) and && (AND) are used for compound conditions.
π Example:
if (myint < 0 || myint == 0) {
Console.WriteLine("Number is less than or equal to zero.");
} else if (myint > 0 && myint <= 10) {
Console.WriteLine("Number is in range 1 to 10.");
} else {
Console.WriteLine("Number is greater than 10.");
}
Switch Statement and Branching
The switch statement can work with booleans, enums, integral types, and strings. It uses one of the following branching statements to exit: break, continue, goto, return, or throw.
π Definition β Switch Statement: A control statement that selects one of many code blocks to execute based on the value of an expression.
While Loop
The while loop executes statements repeatedly as long as a boolean expression remains true. Syntax: while (<boolean expression>) { <statements> }
π Example:
int myint = 0;
while (myint < 10) {
Console.Write("{0} ", myint);
myint++;
}
// Output: 0 1 2 3 4 5 6 7 8 9
Do-While Loop
The do-while loop executes statements at least once before checking the condition. Syntax: do { <statements> } while (<boolean expression>);
For Loop
The for loop uses an initializer list, boolean expression, and iterator list. It supports break to exit early and continue to skip the current iteration.
π Example:
for (int i = 0; i < 20; i++) {
if (i == 10) break;
if (i % 2 == 0) continue;
Console.Write("{0} ", i);
}
// Output: 1 3 5 7 9
Foreach Loop
The foreach loop iterates over all elements in a collection or array. Syntax: foreach (<type> <iteration variable> in <list>) { <statements> }
π Example:
string[] names = {"Cheryl", "Joe", "Matt", "Robert"};
foreach (string person in names) {
Console.WriteLine("{0} ", person);
}
// Output: Cheryl Joe Matt Robert
Methods in C#
Methods are declared using the format: attributes modifiers return-type method-name(parameters) { statements }. Elements are accessed using the dot operator. Object variables are references to the original object, not the objects themselves.
π Definition β Method: A code block that performs a specific task, declared with optional attributes, access modifiers, return type, method name, and parameters.
π Example:
class OneMethod {
public static void Main() {
string mychoice;
OneMethod om = new OneMethod();
mychoice = om.GetChoice();
}
string GetChoice() {
return "example";
}
}
The "this" Pointer
The "this" pointer in methods refers to the current object instance on which the method is called.
Parameter Passing: ref, out, and params
Parameters can be passed in three special ways:
- ref parameter: Passed by reference, allowing the method to modify the original variable
- out parameter: Used for returning values from the method
- params argument: Allows variable number of arguments
π Definition β params: A keyword that allows a method to accept a variable number of arguments of a specified type.
π Example (params):
void ViewAddresses(params string[] names) {
foreach (string name in names) {
Console.WriteLine("Name: {0}", name);
}
}
β Key Takeaways
The most critical concepts to remember are: C# provides multiple integer and floating-point types with different sizes and precision levels. Arrays can be single-dimensional, jagged (array of arrays with varying sizes), or multi-dimensional with fixed dimensions, all using zero-based indexing. Control flow includes if/else with logical operators, switch statements accepting booleans/enums/integrals/strings, and four loop types (while, do-while, for with break/continue, foreach for collections). Methods use the dot operator for access, and parameter passing supports ref (by reference), out (for return values), and params (variable arguments). Object variables are references that point to objects, not the objects themselves.
π§ Quick Revision Questions
- What is the difference between a jagged array and a multi-dimensional array in C#?
- How does the
@verbatim character affect string interpretation? - What are the four types of loops available in C# and when would you use each?
- Explain the difference between
refandoutparameters in method declarations. - How does the
foreachloop work with arrays, and what is its syntax?
π Lecture 6 β Namespaces, Classes, Inheritance, Polymorphism, and Properties
π Overview: This lecture covers core C# object-oriented programming concepts including namespaces for code organization, class construction with constructors and destructors, inheritance hierarchies, polymorphism through virtual and override methods, and properties for encapsulated data access. These fundamentals are essential for building maintainable, object-oriented applications in C#.
ποΈ Topics Covered
Namespaces and nested namespaces with using directives; class declaration, constructors (ctor), destructors (dtor), instance and static members; inheritance with base and derived classes, constructor chaining using base(), and method overriding with new keyword; polymorphism with virtual and override keywords for runtime method dispatch; properties as accessor methods with get and set, including read-only and write-only implementations.
π Lecture Summary
Namespaces
Namespaces allow name reuse β for example, a Console class can reside in multiple libraries. Namespace declaration uses the namespace keyword followed by the namespace name and curly braces containing the code. Nested namespaces can be declared using dot notation (e.g., namespace testnamespace.tutorial) or by nesting namespace blocks. The using directive can rename a long namespace in the current file: using theexample = testnamespace.tutorial.myexample.
π Definition β Namespace: A container for grouping related classes and preventing name conflicts between identical class names in different libraries.
Classes and Constructors
A class is declared with the keyword class followed by the class name, curly braces, and the class body. It has a constructor (ctor) to create objects β ctors do not return any values and initialize class members. A destructor (dtor) is called by the garbage collector for cleanup. Default ctors are written with no arguments when no ctor is explicitly defined. An initializer list can be used to call an alternate constructor: public outputclass() : this("Default Constructor String") { }. Multiple constructors can be defined (overloading).
Class Members: Instance vs Static
Instance members have a separate copy for every new object instance. Static members have only one copy shared across all instances. A static constructor initializes static members and is called only once, with no parameters. Static methods are called on the class itself (e.g., outputclass.staticprinter();). A class can contain: Constructors, Destructors, Fields, Methods, Properties, Indexers, Delegates, Events, and Nested Classes.
π Definition β Static member: A class member that belongs to the class itself rather than any specific instance, with only one copy in memory.
π Example β Instance vs Static members:
Outputclass oc1 = new outputclass("outputclass1");
Outputclass oc2 = new outputclass("outputclass2");
// oc1.printstring and oc2.printstring access different instance variables
// Static members are called via the class: outputclass.staticprinter();
Inheritance
Inheritance introduces the concept of base classes and derived classes, declared as Derived : Base. C# supports only single inheritance (multiple interface inheritance is discussed later). A derived class "is a" base class β it is exactly the same as the base but more specialized. Base classes are automatically initialized before derived classes. Derived classes communicate with base classes using : base() at constructor time or base.x() later.
π Example β Inheritance chain:
Childclass child = new childclass();
child.print();
Output:
Parent Constructor.
Child Constructor.
I'm a Parent Class.
The new keyword is used to override methods (hiding base class methods). To call an overridden method of the base class, cast back to the base type: ((Parent)child).print().
π Definition β Inheritance: A mechanism where a derived class inherits members and behavior from a base class, promoting code reuse and establishing an "is-a" relationship.
Polymorphism
Polymorphism means to invoke derived class methods through a base class reference during runtime. It is handy when a group of related objects is stored in an array/list and you invoke the same method on all of them. Polymorphic methods are declared with the virtual keyword in the base class and the override keyword in derived classes. Polymorphism requires the method signatures to be the same. Because of inheritance, derived classes can be treated as the base class; because of polymorphism, the derived class methods are still called.
π Example β Polymorphism with drawing objects:
DrawingObject[] dobj = new DrawingObject[4];
dobj[0] = new Line();
dobj[1] = new Circle();
dobj[2] = new Square();
dobj[3] = new DrawingObject();
foreach (DrawingObject drawobj in dobj)
{
drawobj.Draw();
}
Output:
I'm a Line.
I'm a Circle.
I'm a Square.
I'm just a generic drawing object.
π Definition β Polymorphism: The ability of a base class reference to call derived class methods at runtime using virtual and override keywords, enabling different behaviors for the same method call.
Properties
Properties allow protected reads and writes to a field of a class, enabling access like fields while maintaining encapsulation. Other languages require custom getter and setter methods, but C# provides a dedicated language feature. Properties use get accessors (which return values) and set accessors (which use the value keyword). Read-only properties have only a get accessor (no set). Write-only properties have only a set accessor (no get).
π Definition β Property: A member that provides a flexible mechanism to read, write, or compute the value of a private field, accessed like a public field but with encapsulated get/set logic.
π Example β Property with get and set:
public int ID
{
get { return m_id; }
set { m_id = value; }
}
// Usage:
cust.ID = 1; // Calls set accessor
Console.WriteLine(cust.ID); // Calls get accessor
π‘ Why this matters: Properties provide controlled access to private fields, allowing validation or logic changes without breaking external code, unlike public fields which expose implementation details.
β Key Takeaways
Namespaces allow name reuse and code organization, with the using directive enabling namespace aliasing. Classes use constructors to initialize objects and destructors for cleanup; instance members are per-object while static members are shared. Inheritance with : base enables base class initialization and communication through constructor chaining and the base keyword. Polymorphism using virtual and override allows runtime method dispatch through base class references, essential for flexible, extensible designs. Properties replace getter/setter methods with field-like syntax, supporting read-only and write-only patterns for controlled data access.
π§ Quick Revision Questions
- What keyword is used to declare a namespace, and how can nested namespaces be accessed from within the parent namespace?
- What is the difference between instance members and static members in a C# class?
- How does the
newkeyword differ fromoverridein the context of inheritance? - What output is produced when a
Lineobject is cast toDrawingObjectand itsDraw()method is called, assuming proper polymorphism? - How would you implement a read-only property in C#, and what accessor would you omit?