Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Modules in C#

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.

Example of Using Namespaces

Here's a simple example of using namespaces to organize your code in C#:

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.

Example of Using Assemblies

When you compile C# code, it gets turned into an assembly (either a .dll or .exe). For example:

 Class Library: Compiling MyLibrary.cs into MyLibrary.dll.


 Executable: Compiling MyApp.cs into MyApp.exe.

These assemblies can then be referenced in other projects or applications.

Understanding Modules in the Context of Assemblies

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

 Namespaces: Used for organizing code.


 Assemblies: Compiled code libraries that can be used by .NET applications, containing
one or more modules.

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:

1. Create a New Project:


o Open Visual Studio.
o Select File > New > Project.
oChoose Windows Forms App (.NET Framework) for a traditional Windows Forms
application, or Windows Forms App for a .NET Core or .NET 5+ project.
o Name your project and click Create.
2. Design the Form:
o Visual Studio opens the Form Designer, where you can drag and drop controls (like
buttons, text boxes, labels, etc.) from the Toolbox onto your form.
o You can set properties of these controls using the Properties window.
3. Add Event Handlers:
o Double-click on a control (e.g., a button) to automatically generate an event handler
method in the code-behind file.
o You can write code inside these event handlers to define what happens when events
(like button clicks) occur.

Example Code

Here's a simple example of a Windows Forms application with a button that displays a message
box when clicked:

1. Design the Form:


o Add a Button to your form (e.g., button1).
2. Code-Behind:
o Open the code-behind file (e.g., Form1.cs).

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();
}

private void button1_Click(object sender, EventArgs e)


{
MessageBox.Show("Button clicked!");
}
}
}

Key Concepts

1. Form: The primary class representing a window or dialog box. You inherit from Form to
create your own forms.

public partial class Form1 : Form


{
// Form initialization and event handling code
}

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.

Key Characteristics of Interfaces

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

Here’s a basic example to illustrate how interfaces are used in C#:

1. Define an Interface:

public interface IAnimal


{
void Eat();
void Sleep();
}
2. Implement the Interface in a Class:
public class Dog : IAnimal
{
public void Eat()
{
Console.WriteLine("Dog is eating.");
}

public void Sleep()


{
Console.WriteLine("Dog is sleeping.");
}
}
3. Using the Interface:
class Program
{
static void Main()
{
IAnimal myDog = new Dog();
myDog.Eat();
myDog.Sleep();
}
}

In this example:

 IAnimal is an interface that defines two methods: Eat and Sleep.


 Dog is a class that implements the IAnimal interface and provides the specific behavior for
Eat and Sleep.
 In the Main method, we use an instance of Dog but refer to it through the IAnimal interface.
This demonstrates polymorphism, as the Dog class is used through the interface type.

Additional Concepts

1. Properties in Interfaces:
 Interfaces can include properties, which must be implemented by the implementing
class.

public interface IShape

double Area { get; }

double Perimeter { get; }


}

2. Default Interface Methods (C# 8.0 and later):


 Interfaces can provide default implementations for methods, although this is less
common and should be used judiciously.
public interface IMyInterface
{
void Method1();
void Method2()
{
// Default implementation
Console.WriteLine("Default implementation");
}
}
3. Explicit Interface Implementation:
 You can implement an interface member explicitly to hide it from the public API
of the class.
public class MyClass : IMyInterface
{
void IMyInterface.Method1()
{
// Explicit implementation
}
}
 To access this method, you need to cast the class instance to the interface type.
4. Interface Inheritance:
 Interfaces can inherit from other interfaces. A class that implements an interface
must also implement all interfaces that the first one inherits.

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:

public class Person : ICloneable


{
public string Name { get; set; }
public int Age { get; set; }

public object Clone()


{
// Shallow copy
return new Person { Name = this.Name, Age = this.Age };
}
}
Usage:
class Program
{
static void Main()
{
Person original = new Person { Name = "John", Age = 30 };
Person clone = (Person)original.Clone();

// Modify clone and observe that the original remains unchanged


clone.Name = "Doe";

Console.WriteLine($"Original: {original.Name}, {original.Age}"); // Output: John, 30


Console.WriteLine($"Clone: {clone.Name}, {clone.Age}"); // Output: Doe, 30
}
}
2. Manual Cloning Methods

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.

Shallow Copy Example:

public class Person

public string Name { get; set; }

public int Age { get; set; }

public Person ShallowCopy()

return (Person)this.MemberwiseClone();

Usage:

class Program

static void Main()

Person original = new Person { Name = "John", Age = 30 };

Person clone = original.ShallowCopy();

// Modify clone and observe that the original remains unchanged

clone.Name = "Doe";
Console.WriteLine($"Original: {original.Name}, {original.Age}"); // Output: John, 30

Console.WriteLine($"Clone: {clone.Name}, {clone.Age}"); // Output: Doe, 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.

Deep Copy Example:

public class Address

public string Street { get; set; }

public class Person

public string Name { get; set; }

public Address Address { get; set; }

public Person DeepCopy()

Person copy = (Person)this.MemberwiseClone();

copy.Address = new Address { Street = this.Address.Street };

return copy;
}

Usage:

class Program

static void Main()

Address address = new Address { Street = "123 Main St" };

Person original = new Person { Name = "John", Address = address };

Person clone = original.DeepCopy();

// Modify clone and observe that the original remains unchanged

clone.Name = "Doe";

clone.Address.Street = "456 Elm St";

Console.WriteLine($"Original Name: {original.Name}, Address:


{original.Address.Street}"); // Output: John, 123 Main St

Console.WriteLine($"Clone Name: {clone.Name}, Address: {clone.Address.Street}"); //


Output: Doe, 456 Elm St

Summary

 Shallow Copy: Uses MemberwiseClone or a manual cloning method. Only copies


references, so changes to referenced objects affect both the original and the copy.
 Deep Copy: Requires explicit cloning of all nested objects. Custom implementation is
needed to ensure that all referenced objects are also cloned.
Choosing between shallow and deep copying depends on your specific needs and how your objects
are structured. For simple cases, MemberwiseClone or a custom shallow copy method might
suffice, but for more complex scenarios involving nested objects, a deep copy approach is
necessary.

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:

public interface IComparable<in T>

int CompareTo(T other);

Implementing IComparable<T>

To implement IComparable<T> in your class, you need to:

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;

public class Person : IComparable<Person>

public string Name { get; set; }


public int Age { get; set; }

// Implement CompareTo method to compare based on Age

public int CompareTo(Person other)

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

static void Main()

Person person1 = new Person { Name = "Alice", Age = 25 };

Person person2 = new Person { Name = "Bob", Age = 30 };

int comparisonResult = person1.CompareTo(person2);

if (comparisonResult < 0)

{
Console.WriteLine($"{person1.Name} is younger than {person2.Name}");

else if (comparisonResult > 0)

Console.WriteLine($"{person1.Name} is older than {person2.Name}");

else

Console.WriteLine($"{person1.Name} and {person2.Name} are the same age");

IComparable Interface for Non-Generic Collections

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:

public class Person : IComparable

public string Name { get; set; }

public int Age { get; set; }

public int CompareTo(object obj)

{
if (obj == null) return 1; // By convention, non-null objects are greater than null

if (obj is Person otherPerson)

return this.Age.CompareTo(otherPerson.Age);

else

throw new ArgumentException("Object is not a Person");

Sorting and Using IComparable<T>

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

static void Main()

List<Person> people = new List<Person>


{

new Person { Name = "Alice", Age = 25 },

new Person { Name = "Bob", Age = 30 },

new Person { Name = "Charlie", Age = 20 }

};

people.Sort(); // Uses CompareTo method for sorting

foreach (Person person in people)

Console.WriteLine($"{person.Name}, {person.Age}");

Summary

 IComparable<T> Interface: Provides a standard way to compare objects of type T.


Implement this interface to enable sorting and comparison based on the natural ordering of
objects.
 CompareTo Method: Must be implemented to define how instances of the class are
compared.
 Usage: Once implemented, your objects can be sorted and compared using standard .NET
collection methods.

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:

 ArrayList: A dynamically resizable array of objects.


 Hashtable: A collection of key/value pairs that are organized based on the hash code of
the key.
 Queue: A first-in, first-out (FIFO) collection of objects.
 Stack: A last-in, first-out (LIFO) collection of objects.
 SortedList: A collection of key/value pairs sorted by the keys.

Example:

using System;

using System.Collections;

class Program

static void Main()

ArrayList list = new ArrayList();

list.Add("Hello");

list.Add(42);

list.Add(DateTime.Now);

foreach (var item in list)


{

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:

 List<T>: A dynamically resizable list of objects of type T.


 Dictionary<TKey, TValue>: A collection of key/value pairs with fast lookup based on
keys.
 HashSet<T>: A collection of unique objects of type T.
 Queue<T>: A first-in, first-out (FIFO) collection of objects of type T.
 Stack<T>: A last-in, first-out (LIFO) collection of objects of type T.
 LinkedList<T>: A doubly linked list of objects of type T.

Example:

using System;

using System.Collections.Generic;

class Program

static void Main()

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

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.

 ConcurrentDictionary<TKey, TValue>: A thread-safe collection of key/value pairs.


 ConcurrentQueue<T>: A thread-safe FIFO (first-in, first-out) collection.
 ConcurrentStack<T>: A thread-safe LIFO (last-in, first-out) collection.
 BlockingCollection<T>: A thread-safe collection that supports bounding and blocking for
producer/consumer scenarios.

Example:

using System;

using System.Collections.Concurrent;

using System.Threading.Tasks;

class Program

static void Main()

var queue = new ConcurrentQueue<int>();

Parallel.For(0, 100, i =>


{

queue.Enqueue(i);

});

while (queue.TryDequeue(out int result))

Console.WriteLine(result);

Summary

 System.Collections: Provides non-generic collections that work with objects of type


System.Object. Includes types like ArrayList, Hashtable, Queue, Stack, and SortedList.
 System.Collections.Generic: Provides type-safe generic collections. Includes types like
List<T>, Dictionary<TKey, TValue>, HashSet<T>, Queue<T>, Stack<T>, and
LinkedList<T>.
 System.Collections.Concurrent: Provides thread-safe collections designed for concurrent
access. Includes types like ConcurrentDictionary<TKey, TValue>, ConcurrentQueue<T>,
ConcurrentStack<T>, and BlockingCollection<T>.

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy