Unit 2
Unit 2
Unit 2
In C#, the term "module" can have different meanings depending on the context in which it's used.
Generally, in C#, "module" might refer to:
1. Namespace: A way to organize and group related classes, structs, interfaces, enums, and
delegates. For example, you might have a namespace called System.Collections which
contains various classes related to collections.
2. Assembly: A compiled code library used by .NET applications. An assembly is a .dll or
.exe file that contains one or more modules. It is the fundamental building block of .NET
applications and can be thought of as a module in this broader sense.
3. Module in C++/CLI: In C++/CLI, a "module" is a single .obj file (object file) that forms
part of a .NET assembly. This usage is specific to C++/CLI and isn't directly applicable to
pure C# programming.
namespace MyApplication.Utilities
{
public class Logger
{
public void Log(string message)
{
// Log message
}
}
}
namespace MyApplication.Models
{
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
}
n this example, the Logger class is part of the MyApplication.Utilities namespace, and the User
class is part of the MyApplication.Models namespace.
When you compile C# code, it gets turned into an assembly (either a .dll or .exe). For example:
When you create an assembly, it can contain multiple modules. Each module is essentially a self-
contained unit of compiled code. However, in most C# applications, you generally deal with
assemblies rather than individual modules directly.
Summary
If you're working with standard C# applications, you're likely interacting with namespaces and
assemblies more than with modules in the strictest sense.
Windows Forms in C#
Windows Forms is a UI framework for building Windows desktop applications in C#. It provides
a straightforward way to create graphical user interfaces (GUIs) using a drag-and-drop designer
and code-behind logic. Here's a brief overview of how to work with Windows Forms in C#:
Getting Started
To create a Windows Forms application in C#, you typically use Visual Studio, which offers a
designer for creating forms and controls. Here's a basic guide:
Example Code
Here's a simple example of a Windows Forms application with a button that displays a message
box when clicked:
Here's the code for a simple form with a button click event handler:
using System;
using System.Windows.Forms;
namespace MyWindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Key Concepts
1. Form: The primary class representing a window or dialog box. You inherit from Form to
create your own forms.
2. Controls: UI elements like buttons, text boxes, labels, etc., that you place on a form. Each
control has properties (e.g., Text, Size) and events (e.g., Click).
3. Events: Actions that can trigger code execution. For instance, clicking a button raises the
Click event.
4. Event Handlers: Methods that handle events. For example, button1_Click is an event
handler for the button's Click event.
5. Properties Window: Allows you to set properties of controls at design time, like changing
the Text property of a button or setting its size.
6. Form Designer: Visual interface in Visual Studio that allows you to design your form by
dragging and dropping controls.
Advanced Topics
1. Custom Controls: You can create custom controls by inheriting from existing controls or
Control class.
2. Data Binding: Windows Forms supports data binding, allowing you to link UI controls to
data sources like databases.
3. Dialog Forms: Special forms used to get user input or display information. Examples
include OpenFileDialog and SaveFileDialog.
4. User Controls: Custom controls that can be reused across different forms or applications.
Summary
Windows Forms provides a rich set of controls and tools for building traditional Windows desktop
applications. It’s especially useful for creating straightforward desktop applications with a
graphical interface. For more advanced or modern UIs, you might consider WPF (Windows
Presentation Foundation) or UWP (Universal Windows Platform), but Windows Forms remains a
popular choice for many applications.
Interface in C#
In C#, an interface is a reference type that defines a contract for classes or structs. It specifies a
set of methods, properties, events, or indexers that implementing classes or structs must provide.
Interfaces are a fundamental part of object-oriented programming in C# and are used to define
capabilities that classes can implement, promoting a form of abstraction and polymorphism.
1. Definition:
o Interfaces define "what" methods or properties a class should implement but not
"how" these members are implemented.
o They do not contain any implementation details themselves.
2. Syntax:
o Interfaces are defined using the interface keyword.
3. Implementation:
o Classes or structs use the : syntax to indicate that they implement an interface.
o A class or struct must provide implementations for all the members defined in the
interface.
4. Multiple Inheritance:
o C# does not support multiple inheritance for classes, but a class can implement
multiple interfaces.
5. Implicit and Explicit Implementation:
o Members of an interface can be implemented either implicitly or explicitly. Implicit
implementation means the member is publicly accessible, while explicit
implementation hides the member from the public API of the class and can only be
accessed through the interface.
Example
1. Define an Interface:
In this example:
Additional Concepts
1. Properties in Interfaces:
Interfaces can include properties, which must be implemented by the implementing
class.
Summary
Interfaces in C# define a contract that classes or structs must adhere to, specifying the methods
and properties they must implement. They are a powerful tool for achieving abstraction, enabling
polymorphism, and ensuring a consistent interface across different classes. Understanding how to
use and implement interfaces effectively is crucial for designing flexible and maintainable object-
oriented systems.
Cloneable objects in C#
In C#, cloning objects refers to creating a new instance of an object that is a copy of an existing
one. This is commonly used when you need a duplicate of an object but want to ensure that the
original and the copy are separate instances, potentially with their own independent states.
Cloning Approaches
1. Shallow Copy:
o Creates a new object, but does not recursively clone the objects referenced by the
fields. Instead, it copies references to those objects.
o Changes to the referenced objects in the cloned object will reflect in the original
object and vice versa.
2. Deep Copy:
o Creates a new object and recursively clones all objects referenced by the fields.
Changes to the cloned object or its referenced objects will not affect the original
object.
Implementing Cloning in C#
To enable cloning in C#, you typically use one of the following approaches:
1. ICloneable Interface
The ICloneable interface provides a standard way to define cloning behavior. It has a single
method, Clone, that should return a copy of the object.
Implementation Example:
Instead of using ICloneable, you can manually implement cloning by defining a method that
creates a new instance of the class and copies over the fields.
return (Person)this.MemberwiseClone();
Usage:
class Program
clone.Name = "Doe";
Console.WriteLine($"Original: {original.Name}, {original.Age}"); // Output: John, 30
3. Deep Copy
For deep copying, you need to ensure that all referenced objects are also cloned. This often
involves implementing a custom clone method.
return copy;
}
Usage:
class Program
clone.Name = "Doe";
Summary
Comparable objects in C#
In C#, if you want to define how objects are compared to each other, you use the IComparable<T>
interface. This interface provides a way for objects of a class or struct to be compared based on a
specific ordering, which can be essential for sorting and comparing instances.
IComparable<T> Interface
The IComparable<T> interface defines a single method, CompareTo, which compares the current
object with another object of the same type and returns an integer that indicates their relative order.
Interface Definition:
Implementing IComparable<T>
1. Implement the CompareTo method to define how instances of your class are compared.
2. Ensure that your implementation provides a meaningful comparison, typically based on the
properties that define the natural ordering of your objects.
Example: Let's implement IComparable<T> in a Person class where persons are compared based
on their age.
using System;
if (other == null) return 1; // By convention, non-null objects are greater than null
// Compare by Age
return this.Age.CompareTo(other.Age);
Usage:
class Program
if (comparisonResult < 0)
{
Console.WriteLine($"{person1.Name} is younger than {person2.Name}");
else
For non-generic collections and legacy code, you might encounter the non-generic IComparable
interface, which does not use generics and works with object. However, it's recommended to use
the generic IComparable<T> wherever possible for type safety and better performance.
Non-Generic Example:
{
if (obj == null) return 1; // By convention, non-null objects are greater than null
return this.Age.CompareTo(otherPerson.Age);
else
When you use classes that implement IComparable<T>, you can leverage sorting functions
provided by .NET, such as those in List<T> or Array.
Example:
using System;
using System.Collections.Generic;
class Program
};
Console.WriteLine($"{person.Name}, {person.Age}");
Summary
By implementing IComparable<T>, you can integrate your objects smoothly with various .NET
frameworks and libraries that rely on object comparison and sorting.
Collections Namepaces in C#
In C#, collections are provided by several namespaces, each offering different types of collections
for various use cases. The main namespaces related to collections are System.Collections,
System.Collections.Generic, and System.Collections.Concurrent. Here's an overview of these
namespaces and the collections they provide:
1. System.Collections
This namespace contains non-generic collection types. These collections work with objects of type
System.Object and can be less type-safe compared to generic collections. Here are some common
classes in this namespace:
Example:
using System;
using System.Collections;
class Program
list.Add("Hello");
list.Add(42);
list.Add(DateTime.Now);
Console.WriteLine(item);
2. System.Collections.Generic
This namespace provides generic collections that are type-safe, meaning they work with a specific
data type and help prevent runtime errors related to type mismatches. Here are some common
classes in this namespace:
Example:
using System;
using System.Collections.Generic;
class Program
names.Add("David");
foreach (string name in names)
Console.WriteLine(name);
3. System.Collections.Concurrent
This namespace provides thread-safe collection classes that are designed for concurrent access,
which means they are safe to use from multiple threads without additional synchronization.
Example:
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
class Program
queue.Enqueue(i);
});
Console.WriteLine(result);
Summary
Each namespace and its collections serve different purposes, from basic object storage to complex
thread-safe operations, and choosing the right one depends on your specific requirements.