π Lecture 7 β Auto-Implemented Properties, Indexers, Structs, and Interfaces
π Overview: This lecture explores four key C# features that enhance object-oriented programming. Auto-implemented properties simplify property declarations, indexers allow classes to be accessed like arrays, structs provide value-type alternatives to classes, and interfaces define contracts for plug-and-play architecture. Understanding these concepts is essential for writing efficient, flexible C# code.
ποΈ Topics Covered
The lecture begins with auto-implemented properties as a simplified syntax for common property patterns. It then covers indexers, including single-parameter and overloaded indexers with multiple parameter types. Next, structs are introduced as value-types with property and method support, along with object initializer syntax. Finally, interfaces are explored as contracts with method signatures only, supporting inheritance and polymorphism.
π Lecture Summary
Auto-Implemented Properties
Auto-implemented properties provide a simplified syntax for the common case where properties simply get and set a backing store. The compiler automatically generates the backing store, eliminating the need for explicit private fields. Properties maintain the same idea of getters and setters but with cleaner code.
π Definition β Auto-implemented property: A property declaration where the compiler automatically creates a hidden backing field, indicated by { get; set; } syntax.
public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
}
π Example: The Customer class uses auto-implemented properties for ID and Name. In the Main method, a Customer object is created and its properties are set directly:
Customer cust = new Customer();
cust.ID = 1;
cust.Name = "Amelio Rosales";
Console.WriteLine("ID: {0}, Name: {1}", cust.ID, cust.Name);
π‘ Why this matters: Auto-implemented properties reduce boilerplate code while maintaining the encapsulation benefits of traditional properties.
Indexers
An indexer enables a class to be treated like an array for internal data access. It is implemented using the this keyword with square bracket syntax and looks similar to a property implementation. Indexers can have any number of parameters of various types (integers, strings, enums) and can be overloaded.
π Definition β Indexer: A special type of property that allows objects to be indexed like arrays, using the this keyword with parameters in square brackets.
π Formula: public returnType this[parameterType parameterName] { get { } set { } }
π Example: A simple integer indexer for a string array:
class IntIndexer
{
private string[] myData;
public IntIndexer(int size)
{
myData = new string[size];
for (int i = 0; i < size; i++)
myData[i] = "empty";
}
public string this[int pos]
{
get { return myData[pos]; }
set { myData[pos] = value; }
}
}
Usage: myInd[9] = "Some Value"; β This sets index position 9 to "Some Value".
Overloaded Indexers
Indexers can be overloaded with different parameter types and counts. This allows accessing data through different keys.
π Formula: public string this[string data] { get { } set { } }
π Example: An overloaded indexer using string parameter:
public string this[string data]
{
get
{
int count = 0;
for (int i = 0; i < arrSize; i++)
if (myData[i] == data) count++;
return count.ToString();
}
set
{
for (int i = 0; i < arrSize; i++)
if (myData[i] == data) myData[i] = value;
}
}
Usage: myInd["empty"] = "no value"; β Replaces all "empty" entries with "no value". Then myInd["no value"] returns the count of "no value" entries.
Multi-Parameter Indexers
Indexers with multiple parameters follow this syntax:
public object this[int param1, ..., int paramN]
{
get { /* process and return some class data */ }
set { /* process and assign some class data */ }
}
Structs
A struct is a value-type, whereas a class is a reference-type. Value types hold their value in memory where they are declared, while reference types hold a reference to an object in memory. When copying a class, C# creates a new copy of the reference; with structs, the actual data is copied directly.
π Key differences: Structs cannot have destructors, cannot have implementation inheritance (but can have interface inheritance). Many built-in types are structs, such as System.Int32 (C# int). The syntax of struct and class are very similar.
π Example: A Rectangle struct with properties:
struct Rectangle
{
private int m_width;
public int Width
{
get { return m_width; }
set { m_width = value; }
}
private int m_height;
public int Height
{
get { return m_height; }
set { m_height = value; }
}
}
Usage:
Rectangle rect1 = new Rectangle();
rect1.Width = 1;
rect1.Height = 3;
Console.WriteLine("rect1: {0}:{1}", rect1.Width, rect1.Height); // Output: 1:3
π Object initializer syntax: A way to initialize a struct without calling a constructor explicitly:
Rectangle rect11 = new Rectangle
{
Width = 1,
Height = 3
};
Interfaces
An interface is declared like a class but has no implementation β only declarations of events, indexers, methods, and/or properties. Classes inherit interfaces and provide the real implementation. Interfaces are essential for plug-n-play architectures where components can be interchanged at will. The interface forces each component to expose specific public members.
π Definition β Interface contract: When a class implements an interface, it guarantees it has all the methods defined in that interface. For example, a class implementing IDisposable guarantees it has a Dispose() method.
π Formula for interface definition:
interface IMyInterface
{
void MethodToImplement();
}
π Example: Interface implementation:
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
Interface Inheritance
Interfaces can inherit from other interfaces:
interface IParentInterface
{
void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface
{
void MethodToImplement();
}
A class implementing IMyInterface must implement both methods. Polymorphism can be achieved using interfaces.
β Key Takeaways
Auto-implemented properties ({ get; set; }) simplify property declarations by having the compiler generate the backing store automatically, reducing code while preserving encapsulation. Indexers use this[key] syntax to make classes accessible like arrays, supporting overloading with different parameter types and counts for flexible data access. Structs are value-types that hold data directly in memory (unlike reference-type classes), cannot have destructors or implementation inheritance, and support object initializer syntax for simplified construction. Interfaces define contracts with method signatures only (using "I" prefix convention), enabling plug-and-play architectures where implementing classes must provide all defined members, and they support both inheritance and polymorphism.
π§ Quick Revision Questions
- What is the key difference between a struct and a class in terms of memory handling?
- How do you declare an indexer that uses a string parameter instead of an integer?
- Can a struct have implementation inheritance? What kind of inheritance can it have?
- What happens if a class implementing an interface does not provide an implementation for one of the interface methods?
- Write the syntax for an object initializer that sets Width to 5 and Height to 10 in a Rectangle struct.
π Lecture 8 β Delegates, Events, and Exception Handling
π Overview: This lecture introduces three fundamental concepts in C# programming: delegates (type-safe function pointers), events (the publisher-subscriber pattern), and exception handling (managing runtime errors). Understanding these concepts is essential for writing flexible, responsive, and robust Windows applications.
ποΈ Topics Covered
The lecture covers delegates as references to methods, demonstrated through a sorting algorithm with a custom comparison delegate; C# events as class members that notify registered methods when triggered, shown with a Windows Forms example; and exception handling using try-catch blocks to manage runtime errors gracefully, including multiple catch handlers for different exception types.
π Lecture Summary
Delegates
A delegate is a reference to a method, similar to function pointers in other languages. Methods are algorithms that operate on data. Sometimes the data needs a special operation, e.g., a comparator in a sorting routine. Without delegates, you would need a bad solution using if-then-else for all types. Two good solutions exist: (1) implement a comparator interface in all types and pass an instance, or (2) use delegates (references to functions) and pass a comparator delegate to the sorting algorithm.
π Definition β delegate: A type-safe object that holds a reference to a method (or multiple methods), allowing methods to be passed as parameters.
π Declaration syntax: public delegate int Comparer(object obj1, object obj2); β This creates a delegate type that can reference any method that takes two objects and returns an integer.
π Example: Full delegate implementation for sorting names by first name:
- Define
Comparerdelegate type - Create
Nameclass withcomparefirstnamesstatic method matching the delegate signature - In
SimpleDelegateclass, instantiate the delegate:Comparer cmp = new Comparer(Name.comparefirstnames); - Pass delegate to sort method:
sd.Sort(cmp); - The
Sortmethod uses the delegate:if (compare(names[i], names[j]) > 0)to compare and swap elements - Output shows names sorted alphabetically by first name
π‘ Why this matters: Delegates enable callback methods and allow algorithms to be decoupled from the data they operate on, making code more reusable and flexible.
Events
A C# event is a class member that is activated whenever the event it was designed for occurs (fires). Anyone interested in the event can register and be notified as soon as the event fires. At the time an event fires, methods registered with the event will be invoked.
Events and delegates work hand in hand. Any class may register one of its methods with the event through a delegate, which specifies the signature of the method registered for the event. The delegate may be pre-defined (.NET delegates) or custom. You assign the delegate to the event, which effectively registers the method that will be called when the event fires.
π Definition β event: A class member that provides a notification mechanism, allowing objects to subscribe and be notified when something occurs.
π Declaration syntax: public event StartDelegate startEvent; β Declares an event of delegate type StartDelegate
π Example: Windows Forms event demonstration:
- Define custom delegate:
public delegate void StartDelegate(); - Create
EventDemoclass inheriting fromForm - Declare custom event:
public event StartDelegate startEvent; - Create a button with Click event:
clickMe.Click += new EventHandler(onClickMeClicked); - Register with custom event:
startEvent += new StartDelegate(onStartEvent); - Fire custom event:
startEvent();(callsonStartEvent) - Result: Two message boxes appear β one at startup ("I Just Started!") and one on button click ("You Clicked My Button!")
π‘ Why this matters: Events enable the observer pattern where multiple objects can react to state changes without the event source knowing about the subscribers, essential for GUI applications.
Exception Handling
There can be unforeseen errors in the program. There are normal errors and exceptional errors, e.g., File I/O error, system out of memory, null pointer exception. Exceptions are "thrown". They are derived from System.Exception class. They have a Message property, contain a StackTrace, and a ToString method. Identifying which exceptions you'll need to handle depends on the routine you're writing, e.g., System.IO.File.OpenRead() could throw SecurityException, ArgumentException, ArgumentNullException, PathTooLongException, DirectoryNotFoundException, UnauthorizedAccessException, FileNotFoundException, or NotSupportedException.
π Definition β exception: An object that represents an error or unexpected condition during program execution, derived from System.Exception.
π Syntax:
try
{
// code that might throw
}
catch (Exception ex)
{
// handle exception
}
π Example: Multiple catch handlers:
try
{
File.OpenRead("nonexistentfile");
}
catch (FileNotFoundException fnfEx)
{
Console.WriteLine(fnfEx.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
The first handler that matches catches the exception. Otherwise, the exception bubbles up the caller stack until someone handles it.
π‘ Why this matters: Proper exception handling prevents program crashes, provides meaningful error messages, and allows graceful recovery from runtime errors.
β Key Takeaways
Delegates are type-safe function references that allow methods to be passed as parameters, making algorithms like sorting more flexible and reusable. Events build on delegates to implement the publisher-subscriber pattern, where objects can register interest in notifications and be called when events fire β essential for GUI programming. Exception handling uses try-catch blocks to manage runtime errors, with more specific catch handlers evaluated first and exceptions bubbling up the call stack if unhandled. All exceptions derive from System.Exception and provide detailed information through properties like Message and StackTrace. The += operator is used both for registering delegates with events and for adding multiple handlers to a single event.
π§ Quick Revision Questions
- What is a delegate and how does it differ from a regular method call?
- How do you declare a custom event in C# and what role does a delegate play in events?
- What happens when an exception is not caught in the current method?
- Why would you use multiple catch blocks for a single try block?
- What is the
+=syntax doing when used with events likeclickMe.Click += new EventHandler(...)?
π Lecture 9 β Exception Handling, Attributes, Enums, Operator Overloading, and Generic Collections
π Overview: This lecture covers several important C# programming concepts, including resource cleanup using the finally block, adding declarative information to code with attributes, working with strongly typed constants using enums, extending operators for custom types through operator overloading, and using type-safe generic collections. These concepts are fundamental for writing robust, maintainable, and type-safe C# applications.
ποΈ Topics Covered
The lecture begins with exception handling using the finally block for resource cleanup, then moves to attributes which add metadata to programs. It covers enums as strongly typed constants with practical usage examples, followed by operator overloading for custom types. The lecture concludes with generic collections including List and Dictionary for type-safe data management.
π Lecture Summary
Exception Handling and the Finally Block
Exception can leave your program in an inconsistent state by not releasing resources or doing some other type of cleanup. Sometimes you need to perform clean up actions whether or not your program succeeds. These are good candidates for using a finally block, for example, a filestream must be closed. The finally block ensures cleanup code executes regardless of whether an exception occurred.
Using System;
Using System.IO;
Class finallydemo
{
Static void Main(string[] args)
{
Filestream outstream = null;
Filestream instream = null;
Try
{
Outstream = File.openwrite("destinationfile.txt");
Instream = File.openread("bogusinputfile.txt");
}
Catch (Exception ex)
{
Console.writeline(ex.tostring());
}
Finally
{
If (outstream != null)
{
Outstream.Close();
Console.writeline("outstream closed.");
}
If (instream != null)
{
Instream.Close();
Console.writeline("instream closed.");
}
}
}
}
The alternate would be to duplicate code after catch and in catch. But finally is a neat cleanup solution.
Attributes
Attributes add declarative information to your programs. They are used for various purposes during runtime. They can be used at design time by application development tools. For example, DllImportAttribute allows a program to communicate with Win32 libraries. ObsoleteAttribute causes a compile-time warning to appear. Such things would be difficult to accomplish with normal code. Attributes add metadata to your programs.
When your C# program is compiled, it creates a file called an assembly, which is normally an executable or DLL library. Assemblies are self-describing because they have metadata. Via reflection, a program's attributes can be retrieved from its assembly metadata. Attributes are classes that can be written in C# and are used to decorate your code with declarative information.
Attributes are generally applied physically in front of type and type member declarations. They are declared with square brackets, "[" and "]" surrounding the attribute such as "[obsoleteattribute]". The "Attribute" part of the attribute name is optional, i.e. "[Obsolete]" is correct as well. Parameter lists are also possible.
Using System;
Class basicattributedemo
{
[Obsolete]
Public void myfirstdeprecatedmethod()
{
Console.writeline("Called myfirstdeprecatedmethod().");
}
[obsoleteattribute]
Public void myseconddeprecatedmethod()
{
Console.writeline("Called myseconddeprecatedmethod().");
}
[Obsolete("You shouldn't use this method anymore.")]
Public void mythirddeprecatedmethod()
{
Console.writeline("Called mythirddeprecatedmethod().");
}
[stathread]
Static void Main(string[] args)
{
Basicattributedemo attrdemo = new basicattributedemo();
Attrdemo.myfirstdeprecatedmethod();
Attrdemo.myseconddeprecatedmethod();
Attrdemo.mythirddeprecatedmethod();
}
}
When you compile this program you'll see compilation warnings indicating that the methods are obsolete. Stathread is a common attribute that stands for Single Threaded Apartment model which is used for communicating with unmanaged COM.
Attribute parameters can be either positional parameters or named parameters. Usually named parameters with optional stuff, but positional can be optional as well. For example, [Obsolete("You shouldn't use this method anymore.", true)] will give an error instead of warning. The attribute DllImportAttribute has both positional and named parameters: [dllimport("User32.dll", entrypoint="messagebox")]. Positional parameters come before named parameters. There is no order requirement on named parameters.
Using System;
[assembly: clscompliant(true)]
Public class attributetargetdemo
{
Public void nonclscompliantmethod(uint nclsparam)
{
Console.writeline("Called nonclscompliantmethod().");
}
[stathread]
Static void Main(string[] args)
{
uint myuint = 0;
Attributetargetdemo tgtdemo = new attributetargetdemo();
Tgtdemo.nonclscompliantmethod(myuint);
}
}
We rarely write new attributes but we use them extensively.
Enums
Enums (or enumerations) are strongly typed constants. They are unique types that allow you to assign symbolic names to integral values. An enum of one type may not be implicitly assigned to an enum of another type (even though the underlying value of their members is the same). All assignments between different enum types and integral types require an explicit cast. It allows you to work with integral values, but using a meaningful name, like North, South, East, and West instead of integers 0, 1, 2, and 3. The C# type enum inherits the Base Class Library (BCL) type Enum.
π Definition β Enum: A distinct type consisting of a set of named constants called the enumerator list.
Using System;
// declares the enum
Public enum Volume
{
Low,
Medium,
High
}
// demonstrates how to use the enum
Class enumswitch
{
Static void Main()
{
Volume myvolume = Volume.Medium;
Switch (myvolume)
{
Case Volume.Low:
Console.writeline("The volume has been turned Down.");
Break;
Case Volume.Medium:
Console.writeline("The volume is in the middle.");
Break;
Case Volume.High:
Console.writeline("The volume has been turned up.");
Break;
}
Console.readline();
}
}
Default underlying type of an enum is int. It can be changed by specifying a base. Valid base types include byte, sbyte, short, ushort, int, uint, long, and ulong. Default value of the first member is 0. You can assign any member any value. If it is unassigned it gets +1 the value of its predecessor.
Public enum Volume : byte
{
Low = 1,
Medium,
High
}
To convert user input to enum:
String volstring = Console.readline();
Int volint = Int32.Parse(volstring);
Volume myvolume = (Volume)volint;
Enum inherits from System.Enum in base class library.
To get a list of member names from Volume enum:
Foreach (string volume in Enum.getnames(typeof(Volume)))
{
Console.writeline("Volume Member: {0}\n Value: {1}",
Volume, (byte)Enum.Parse(typeof(Volume), volume));
}
To enumerate values:
Foreach (byte val in Enum.getvalues(typeof(Volume)))
{
Console.writeline("Volume Value: {0}\n Member: {1}",
Val, Enum.getname(typeof(Volume), val));
}
Operator Overloading
You can add operators to your own types, for example, a Matrix type can have an add and a dot product operator.
Matrix result = mat1.Add(mat2); // instance
Matrix result = Matrix.Add(mat1, mat2); // static
Matrix result = mat1.dotproduct(mat2).dotproduct(mat3);
Matrix result = mat1 + mat2; // operator overload
Matrix result = mat1 * mat2 * mat3 * mat4; // operator overload
It should not be used when its not natural to be used. Its implementation syntax is:
Public static Matrix operator *(Matrix mat1, Matrix mat2)
{
// dot product implementation
}
Here is a complete example:
Using System;
Class Matrix
{
Public const int dimsize = 3;
Private double[,] m_matrix = new double[dimsize, dimsize];
Public double this[int x, int y]
{
Get { return m_matrix[x, y]; }
Set { m_matrix[x, y] = value; }
}
Public static Matrix operator +(Matrix mat1, Matrix mat2)
{
Matrix newmatrix = new Matrix();
For (int x = 0; x < dimsize; x++)
For (int y = 0; y < dimsize; y++)
Newmatrix[x, y] = mat1[x, y] + mat2[x, y];
Return newmatrix;
}
}
π Definition β Operator Overloading: Defining how built-in operators (like +, -, *) work with user-defined types.
π Rule: Overloaded operators must be static. They must be declared in the class for which the operator is defined. It is required that matching operators are both defined, e.g. == and !=, so that the behavior is consistent.
Access modifiers on types and assemblies provide encapsulation. They are: private, protected, internal, protected internal, and public.
Generic Collections
There is a very useful List collection. It is better than ArrayList of objects in earlier .NET versions. Another useful collection is Dictionary<TKey, TValue> vs. a non-generic Hashtable of objects. We write using System.Collections.Generic to include these collections.
List<int> myints = new List<int>();
Myints.Add(1);
Myints.Add(2);
Myints.Add(3);
For (int i = 0; i < myints.Count; i++)
{
Console.writeline("myints: {0}", myints[i]);
}
To work with custom objects in dictionaries:
Public class Customer
{
Public Customer(int id, string name)
{
ID = id;
Name = name;
}
Public int ID { Get; Set; }
Public string Name { Get; Set; }
}
Dictionary<int, Customer> customers = new Dictionary<int, Customer>();
Customer cust1 = new Customer(1, "Cust 1");
Customer cust2 = new Customer(2, "Cust 2");
Customer cust3 = new Customer(3, "Cust 3");
Customers.Add(cust1.ID, cust1);
Customers.Add(cust2.ID, cust2);
Customers.Add(cust3.ID, cust3);
Foreach (keyvaluepair<int, Customer> custkeyval in customers)
{
Console.writeline(
"Customer ID: {0}, Name: {1}",
Custkeyval.Key,
Custkeyval.Value.Name);
}
π‘ Why this matters: Generic collections provide type safety at compile time, eliminating the need for runtime type checking and boxing/unboxing, making code faster and safer.
β Key Takeaways
The finally block is essential for resource cleanup code that must execute whether an exception occurs or not, particularly for file streams and other unmanaged resources. Attributes add metadata to assemblies and can be retrieved via reflection, with the Attribute suffix being optional in their declaration. Enums provide strongly typed constants with an underlying integral type (default int), and values can be iterated using Enum.GetNames and Enum.GetValues. Operator overloading must use static methods within the class, and matching operators (like == and !=) must be defined together. Generic collections like List<T> and Dictionary<TKey, TValue> provide type-safe alternatives to non-generic collections, requiring the System.Collections.Generic namespace.
π§ Quick Revision Questions
-
What is the purpose of the finally block in exception handling, and why is it preferred over duplicating cleanup code?
-
How do you declare an attribute in C#, and what is the significance of the "Attribute" suffix being optional?
-
What is the default underlying type of an enum, and how can you change it to a different integral type?
-
What are the requirements for implementing operator overloading in C# (specifically regarding static modifier and matching operators)?
-
What namespace is required for using generic collections like List<T> and Dictionary<TKey, TValue>, and what advantage do they offer over non-generic collections?
π Lecture 10 β Anonymous Methods, Debugging, XML Parsing & Writing
π Overview: This lecture covers three distinct topics: anonymous methods in C# for simplifying event handling, debugging techniques in Visual Studio, and comprehensive XML processing including reading, writing, and updating XML documents using both XmlReader and XmlDocument classes. These skills are essential for writing efficient code, troubleshooting applications, and handling data exchange formats.
ποΈ Topics Covered
Anonymous methods and their use with delegates and events, including parameter handling; nullable value types with the ? operator and null-coalescing operator ??; debugging in Visual Studio using breakpoints, watch windows, and conditional breakpoints; XML structure and syntax; reading XML with XmlReader and XmlDocument classes; XPath querying with SelectSingleNode and SelectNodes; writing XML with XmlWriter and XmlDocument; updating XML documents using XmlDocument.
π Lecture Summary
Anonymous Methods
Anonymous methods are methods without a name, used directly with delegates and events to reduce code. Instead of declaring a delegate, writing a separate method, declaring an event based on the delegate, and hooking the handler up, you simply use the keyword delegate followed by the method body directly in the event subscription. This results in much less code. Parameters can be skipped when not needed.
π Definition β Anonymous Method: A method without a name that is hooked up directly to an event using the delegate keyword followed by the method body.
π Example (without parameters):
Button btnhello = new Button();
btnhello.Text = "Hello";
btnhello.Click += delegate { MessageBox.Show("Hello"); };
π Example (with parameters):
Button btngoodbye = new Button();
btngoodbye.Text = "Goodbye";
btngoodbye.Click += delegate(object sender, EventArgs e)
{
string message = (sender as Button).Text;
MessageBox.Show(message);
};
Nullable Types
You can create nullable value types by appending a question mark (?) to a type name. This allows value types (like int, DateTime) to hold null values. The null-coalescing operator (??) provides a shorthand for checking if a nullable type is null and assigning a default value.
π Definition β Nullable Type: A value type that can also be assigned null, created by appending ? to the type name (e.g., int?).
π Formula: variable ?? defaultValue β If variable is not null, use its value; otherwise use defaultValue.
π Example:
int? unitsInStock = 5;
DateTime? startDate = DateTime.Now;
startDate = null;
// Without null-coalescing operator
int availableUnits;
if (unitsInStock == null)
availableUnits = 0;
else
availableUnits = (int)unitsInStock;
// With null-coalescing operator (equivalent)
int availableUnits = unitsInStock ?? 0;
π‘ Why this matters: Nullable types and the ?? operator provide clean, concise code for handling potentially missing data without complex if-else structures.
Debugging in Visual Studio
Debugging helps find and fix errors by printing output or using breakpoints that stop program execution. Press F5 to run with debugging; execution will stop at any breakpoint. You can hover over variables to see their current values. The Locals, Watch, Call Stack, and Immediate Window provide different information about the program state. Changes made during debugging affect the current execution. Conditional breakpoints can have a hit count and conditions for when to stop execution.
XML Basics
XML (Extensible Markup Language) is widely used for exchanging data. It is readable for both humans and machines. It is a stricter version of HTML. XML is made of tags, attributes, and values.
π Example of simple XML:
<users>
<user name="John Doe" age="42" />
<user name="Jane Doe" age="39" />
</users>
π Example of larger XML (Euro exchange rates):
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2012-12-18">
<Cube currency="USD" rate="1.3178"/>
<Cube currency="JPY" rate="110.53"/>
<!-- more currency cubes -->
</Cube>
</Cube>
</gesmes:Envelope>
Reading XML with XmlReader
The XmlReader class provides a fast, forward-only, read-only cursor for processing XML. It reads one element at a time and uses less memory than XmlDocument.
π Definition β XmlReader: A fast, read-only, forward-only cursor that processes XML one element at a time.
π Example (reading Euro exchange rates):
XmlReader xmlreader = XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
while (xmlreader.Read())
{
if ((xmlreader.NodeType == XmlNodeType.Element) && (xmlreader.Name == "Cube"))
{
if (xmlreader.HasAttributes)
Console.WriteLine(xmlreader.GetAttribute("currency") + ": " + xmlreader.GetAttribute("rate"));
}
}
Reading XML with XmlDocument
The XmlDocument class reads the entire document into memory, allowing forward and backward navigation and XPath searches. DocumentElement is the root element, and ChildNodes is the set of children of any node.
π Definition β XPath: A cross-platform XML Query language used to navigate and select nodes in an XML document.
π Example (same data using XmlDocument):
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
foreach (XmlNode xmlnode in xmldoc.DocumentElement.ChildNodes[2].ChildNodes[0].ChildNodes)
Console.WriteLine(xmlnode.Attributes["currency"].Value + ": " + xmlnode.Attributes["rate"].Value);
π Example (using XPath with SelectSingleNode for RSS title):
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("http://rss.cnn.com/rss/edition_world.rss");
XmlNode titlenode = xmldoc.SelectSingleNode("//rss/channel/title");
if (titlenode != null)
Console.WriteLine(titlenode.InnerText);
π Example (using XPath with SelectNodes for multiple items):
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("http://rss.cnn.com/rss/edition_world.rss");
XmlNodeList itemnodes = xmldoc.SelectNodes("//rss/channel/item");
foreach (XmlNode itemnode in itemnodes)
{
XmlNode titlenode = itemnode.SelectSingleNode("title");
XmlNode datenode = itemnode.SelectSingleNode("pubDate");
if ((titlenode != null) && (datenode != null))
Console.WriteLine(datenode.InnerText + ": " + titlenode.InnerText);
}
π‘ Why this matters: XmlReader is best for simple, forward-only processing with minimal memory, while XmlDocument is better for complex navigation, updates, and XPath queries.
Writing XML with XmlWriter
The XmlWriter class creates XML documents sequentially. It provides methods like WriteStartDocument(), WriteStartElement(), WriteAttributeString(), WriteString(), WriteEndElement(), and WriteEndDocument().
π Example:
XmlWriter xmlwriter = XmlWriter.Create("test.xml");
xmlwriter.WriteStartDocument();
xmlwriter.WriteStartElement("users");
xmlwriter.WriteStartElement("user");
xmlwriter.WriteAttributeString("age", "42");
xmlwriter.WriteString("John Doe");
xmlwriter.WriteEndElement();
xmlwriter.WriteStartElement("user");
xmlwriter.WriteAttributeString("age", "39");
xmlwriter.WriteString("Jane Doe");
xmlwriter.WriteEndDocument();
xmlwriter.Close();
This produces:
<users>
<user age="42">John Doe</user>
<user age="39">Jane Doe</user>
</users>
Writing/Updating XML with XmlDocument
Writing with XmlDocument uses methods like CreateElement(), CreateAttribute(), AppendChild(), and Save(). This approach is especially useful for updates.
π Example (creating XML):
XmlDocument xmldoc = new XmlDocument();
XmlNode rootnode = xmldoc.CreateElement("users");
xmldoc.AppendChild(rootnode);
XmlNode usernode = xmldoc.CreateElement("user");
XmlAttribute attribute = xmldoc.CreateAttribute("age");
attribute.Value = "42";
usernode.Attributes.Append(attribute);
usernode.InnerText = "John Doe";
rootnode.AppendChild(usernode);
// ... more nodes
xmldoc.Save("test-doc.xml");
π Example (updating XML β incrementing ages):
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("test-doc.xml");
XmlNodeList usernodes = xmldoc.SelectNodes("//users/user");
foreach (XmlNode usernode in usernodes)
{
int age = int.Parse(usernode.Attributes["age"].Value);
usernode.Attributes["age"].Value = (age + 1).ToString();
}
xmldoc.Save("test-doc.xml");
π‘ Why this matters: Updating XML with XmlDocument is much easier than with XmlReader/XmlWriter combination, as XmlDocument allows direct modification of nodes in memory.
β Key Takeaways
Anonymous methods allow you to write event handlers inline using the delegate keyword, eliminating the need for separate named methods and reducing code. Nullable types (int?, DateTime?) enable value types to hold null, and the ?? operator provides a concise default value assignment. Debugging in Visual Studio with breakpoints, conditional breakpoints, and inspection windows (Locals, Watch, Call Stack, Immediate Window) is essential for finding and fixing bugs. For XML processing, use XmlReader for fast, forward-only reading with minimal memory, and XmlDocument for bidirectional navigation, XPath queries, and document updates. Writing XML can be done with XmlWriter for sequential creation or XmlDocument for more flexible, in-memory construction and modification.
π§ Quick Revision Questions
- What is an anonymous method and how is it declared in C# event handling?
- How do you create a nullable integer variable, and what does the
??operator do? - What is the difference between XmlReader and XmlDocument when reading XML files?
- What XPath method would you use to select a single node, and what method would you use to select multiple nodes?
- How would you update all "age" attributes in an XML document by incrementing them by 1 using XmlDocument?
π Lecture 11 β Extension Methods, File I/O, and Reflection in C#
π Overview: This lecture covers three important C# programming concepts: extension methods for adding functionality to existing types, file and directory handling using the System.IO namespace, and reflection for examining type metadata at runtime. These techniques are essential for writing flexible, maintainable code and building systems that can adapt to dynamic requirements.
ποΈ Topics Covered
The lecture begins with extension methods as a way to simplify code by extending existing types. It then moves into comprehensive file and directory operations including reading, writing, appending, deleting, renaming files and directories using File, Directory, StreamWriter, FileInfo, and DirectoryInfo classes. The final major topic is reflection, covering how to get type information, enumerate type members, invoke methods dynamically, and build a complete profile save/load system using reflection.
π Lecture Summary
Extension Methods
Extension methods allow you to add new methods to existing types without modifying them. They are defined as static methods in a static class, with the first parameter containing the this keyword to specify which type the method extends. This provides a cleaner syntax for utility operations.
π Definition β Extension Method: A static method that appears to be an instance method of a type, defined in a static class with the first parameter prefixed by this.
π Example: Instead of calling MyUtils.IsNumeric("4"), you can create an extension method so you can call "4".IsNumeric(). The extension method is defined as public static bool IsNumeric(this string s) that internally uses float.TryParse(s, out output).
File Handling Basics
The System.IO namespace provides classes for file operations. File.Exists() checks if a file exists. File.ReadAllText() reads entire file content into a string. File.WriteAllText() overwrites file content. File.AppendAllText() adds content without overwriting.
π Example: Check if "test.txt" exists, read and display its current content, then prompt user for new content and write it:
if(File.Exists("test.txt"))
{
string content = File.ReadAllText("test.txt");
Console.WriteLine("Current content of file:");
Console.WriteLine(content);
}
Console.WriteLine("Please enter new content for the file:");
string newContent = Console.ReadLine();
File.WriteAllText("test.txt", newContent);
π Example: Continuous editing with append until user types "exit":
Console.WriteLine("Please enter new content - type exit and press enter to finish editing:");
string newContent = Console.ReadLine();
while (newContent != "exit")
{
File.AppendAllText("test.txt", newContent + Environment.NewLine);
newContent = Console.ReadLine();
}
Using Statement and StreamWriter
The using statement ensures proper disposal of unmanaged resources like file streams. When you create a StreamWriter inside a using block, its Dispose() method is automatically called at the end, which closes the file and releases system resources.
π Example: Using StreamWriter with using statement:
using (StreamWriter sw = new StreamWriter("test.txt"))
{
string newContent = Console.ReadLine();
while (newContent != "exit")
{
sw.Write(newContent + Environment.NewLine);
newContent = Console.ReadLine();
}
}
π‘ Why this matters: Without using, you would need to manually call sw.Close() to ensure the file is properly closed, which can lead to resource leaks if forgotten.
File and Directory Operations
- Delete a file:
File.Delete("test.txt") - Delete a directory:
Directory.Delete("testdir") - Rename a file: Use
File.Move("oldname.txt", "newname.txt") - Rename a directory: Use
Directory.Move("olddir", "newdir") - Create a directory:
Directory.CreateDirectory("newdirname")
π Example: Rename a file with user input:
if (File.Exists("test.txt"))
{
Console.WriteLine("Please enter a new name for this file:");
string newFileName = Console.ReadLine();
if (newFileName != String.Empty)
{
File.Move("test.txt", newFileName);
if (File.Exists(newFileName))
{
Console.WriteLine("The file was renamed to " + newFileName);
}
}
}
FileInfo and DirectoryInfo
FileInfo provides detailed information about a specific file, such as name, size, and last modified date. DirectoryInfo gives information about a directory and can enumerate its files and subdirectories.
π Definition β FileInfo: An object that provides properties and instance methods for creating, copying, deleting, moving, and opening files.
π Example: Get information about the executing assembly's file:
FileInfo fi = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
if (fi != null)
Console.WriteLine(String.Format("Information about file: {0}, {1} bytes", fi.Name, fi.Length));
π Example: List all files in a directory using DirectoryInfo:
DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
if (di != null)
{
FileInfo[] subFiles = di.GetFiles();
Console.WriteLine("Files:");
foreach (FileInfo subFile in subFiles)
{
Console.WriteLine(" " + subFile.Name + " (" + subFile.Length + " bytes)");
}
}
π Example: List subdirectories:
DirectoryInfo[] subDirs = di.GetDirectories();
Console.WriteLine("Directories:");
foreach (DirectoryInfo subDir in subDirs)
{
Console.WriteLine(" " + subDir.Name);
}
Introduction to Reflection
Reflection allows you to examine and interact with type metadata at runtime. Using System.Reflection, you can get type information, enumerate properties, methods, constructors, and even invoke them dynamically.
π Definition β Reflection: The ability to obtain information about types, their members, and to invoke members at runtime, even when the type is not known at compile time.
π Example: Get type names at runtime:
string test = "test";
Console.WriteLine(test.GetType().FullName); // System.String
Console.WriteLine(typeof(Int32).FullName); // System.Int32
π Example: List all types in the current assembly:
Assembly assembly = Assembly.GetExecutingAssembly();
Type[] assemblyTypes = assembly.GetTypes();
foreach(Type t in assemblyTypes)
Console.WriteLine(t.Name);
Invoking Methods with Reflection
Using reflection, you can create instances of types and invoke their methods dynamically, even when the type is not known at compile time.
π Example: Create instance and invoke method via reflection:
Type testType = typeof(TestClass);
ConstructorInfo ctor = testType.GetConstructor(System.Type.EmptyTypes);
if (ctor != null)
{
object instance = ctor.Invoke(null);
MethodInfo methodInfo = testType.GetMethod("TestMethod");
Console.WriteLine(methodInfo.Invoke(instance, new object[] { 10 }));
}
Complete Profile Save/Load System with Reflection
This comprehensive example demonstrates how to build a persistent settings system that saves and loads object properties automatically using reflection, without knowing the property names at compile time.
π Definition β PropertyInfo: A reflection object that provides access to a property of a type, including getting and setting its value.
π Key elements of the Person class:
Load()method: Reads "settings.dat", parses each line as "PropertyName|Value", finds the property usingType.GetProperty(), and sets its value using the customSetProperty()methodSave()method: Gets all properties usingType.GetProperties(), writes each as "Name|Value" to "settings.dat"SetProperty()method: Handles type conversion (Int32, String) and callsPropertyInfo.SetValue()with appropriate conversion
π Example: Using the profile system:
Person person = new Person();
person.Load();
if ((person.Age > 0) && (person.Name != String.Empty))
{
Console.WriteLine("Hi " + person.Name + " - you are " + person.Age + " years old!");
}
else
{
Console.WriteLine("I don't seem to know much about you. Please enter the following information:");
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
Console.WriteLine(propertyInfo.Name + ":");
person.SetProperty(propertyInfo, Console.ReadLine());
}
person.Save();
Console.WriteLine("Thank you! I have saved your information for next time.");
}
π‘ Why this matters: This pattern allows creating generic save/load systems that work with any object type without writing specific code for each property.
β Key Takeaways
Extension methods provide syntactic sugar for adding functionality to existing types without inheritance. File I/O operations in System.IO include reading, writing, appending, deleting, renaming files and directories, with using statement being essential for proper resource management. Reflection is a powerful meta-programming technique that enables runtime type inspection, dynamic method invocation, and building flexible systems like automatic property persistence. The profile save/load example demonstrates how to combine reflection with file I/O to create reusable object serialization without explicit property mapping. Understanding when and how to use these techniques distinguishes basic programming from advanced, maintainable application development.
π§ Quick Revision Questions
- How do you define an extension method in C#? What special keyword and parameter arrangement is required?
- What is the difference between
File.WriteAllText()andFile.AppendAllText()? When would you use each? - Why is the
usingstatement important when working with file streams likeStreamWriter? - How can you use
FileInfoto get the size of a file andDirectoryInfoto list all files in a directory? - In the reflection-based profile save/load system, how does the
SetProperty()method handle different data types like integers versus strings?