0% found this document useful (0 votes)
13 views

MICTE 3rd Visual Programming Notes

The document provides an overview of Visual Programming and its significance in software development, highlighting its graphical interface, ease of use for non-programmers, and rapid prototyping capabilities. It discusses various visual programming practices, including WYSIWYG editors, block-based programming, and event-driven programming, particularly in the context of C#. Additionally, it covers Rapid Application Development (RAD) tools and techniques that facilitate quick software delivery and user involvement in the development process.

Uploaded by

Nischal Ghimire
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

MICTE 3rd Visual Programming Notes

The document provides an overview of Visual Programming and its significance in software development, highlighting its graphical interface, ease of use for non-programmers, and rapid prototyping capabilities. It discusses various visual programming practices, including WYSIWYG editors, block-based programming, and event-driven programming, particularly in the context of C#. Additionally, it covers Rapid Application Development (RAD) tools and techniques that facilitate quick software delivery and user involvement in the development process.

Uploaded by

Nischal Ghimire
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 91

1

Unit 1
Visual Programming and C#
1.1. Overview of Visual Programming, The need of Visual Programming
Visual Programming is a programming methodology that allows developers to create software
using graphical elements instead of writing text-based code. This approach is especially common in
environments where the development of graphical user interfaces (GUIs) or interactive elements is a
primary focus. Visual programming environments provide tools such as drag-and-drop interfaces,
flowcharts, and block diagrams that represent the logic and structure of a program visually. This visual
approach can often be more intuitive and easier to learn, especially for those without a strong
programming background.

Key Characteristics of Visual Programming:


 Graphical Interface: Uses icons, symbols, and other visual elements to represent the components
and logic of a program.
 Drag-and-Drop Functionality: Allows users to drag predefined blocks or components to build a
program.
 Abstraction: Simplifies complex code by abstracting it into visual blocks or elements.
 Immediate Feedback: Many visual programming environments offer real-time feedback, making
it easier to test and debug.

The Need for Visual Programming


Visual programming addresses several challenges and requirements in the software development
process:
1. Ease of Use for Non-Programmers: Visual programming lowers the barrier to entry for those
who may not have extensive coding experience. By representing code with visual elements, it
becomes easier for beginners, educators, or those in non-technical fields to engage with
programming.
2. Rapid Prototyping and Development: Visual programming environments enable developers to
quickly prototype and iterate on designs. This is particularly useful in environments where quick
feedback and adjustments are necessary, such as in UI/UX design or educational tools.
3. Error Reduction: By providing a more intuitive and visual way to build programs, visual
programming can reduce certain types of errors, such as syntax errors or logical inconsistencies,
that are common in text-based coding.
4. Improved Readability: Visual representations can make code more understandable, even for
non- programmers, as it provides a clear visual structure.
5. Integration with GUI Development: Visual programming is often integrated with GUI
development environments, making it a natural fit for applications that rely heavily on user
interfaces. Tools like Visual Studio allow developers to design UIs visually and automatically
generate the underlying code.
6. Enhancing Collaboration: In a team environment, visual programming can facilitate better
collaboration between developers and non-developers (such as designers or product managers) by
providing a shared, visual language that everyone can understand.
7. Supporting Event-Driven Programming: Visual programming environments are particularly
well-suited to event-driven programming, where the program's flow is determined by events such
as user inputs. The visual approach makes it easier to map out and manage these events.

Examples of Visual Programming Environments:


 Scratch: A block-based visual programming language aimed at children and beginners.
 MIT App Inventor: A visual programming tool for creating mobile apps.
 LabVIEW: A visual programming environment used primarily for data acquisition, instrument
control, and industrial automation.
2

 Microsoft Visual Studio (WinForms and WPF): Allows developers to design user interfaces
visually while writing the underlying code in C# or other .NET languages.

1.2. Graphical User Interface and different types of Visual Programming Practices
Graphical User Interface (GUI)
A Graphical User Interface (GUI) is a user interface that allows users to interact with software
applications through graphical elements like buttons, icons, menus, and other visual indicators, rather
than using text-based commands. GUIs make software more intuitive and accessible, allowing users to
navigate and operate programs through visual elements.
Key Components of a GUI:
 Windows: The main containers that hold different elements like buttons, text boxes, and menus.
 Buttons: Clickable elements that perform actions when pressed.
 Text Boxes: Fields where users can input text.
 Labels: Text elements that provide information or describe other elements.
 Menus: Lists of options or commands that users can select from.
 Icons: Small images representing files, applications, or commands.
Benefits of GUI:
 User-Friendly: Easier for non-technical users to operate software.
 Consistency: Provides a consistent interface across applications, making it easier to learn and use
new software.
 Interactivity: Offers immediate visual feedback and interactivity, enhancing user experience.

Different Types of Visual Programming Practices


Visual programming practices can vary depending on the tools and methodologies used. Here are some
common types:
1. WYSIWYG (What You See Is What You Get) Editors:
o Overview: WYSIWYG editors allow developers to create GUIs by visually assembling
interface components, with the underlying code automatically generated in the background.
These editors provide a real-time preview of what the final interface will look like.
o Examples:
 Dreamweaver: A WYSIWYG HTML editor for web development.
 Visual Studio WinForms Designer: Allows developers to design Windows Forms
applications visually.
2. Block-Based Programming:
o Overview: Block-based programming allows users to create programs by stacking blocks that
represent different commands, logic, and functions. Each block corresponds to a specific piece
of code or an action, and they snap together like puzzle pieces.
o Examples:
 Scratch: An educational programming environment where users drag and drop code
blocks to create animations, games, and interactive stories.
 MIT App Inventor: A tool for building Android applications using a block-based interface.
3. Flowchart-Based Programming:
o Overview: Flowchart-based programming uses flowcharts to represent the logic and flow of a
program. Users create programs by connecting visual representations of processes, decisions,
and actions.
o Examples:
 LabVIEW: A system-design platform and development environment for visual
programming, especially in engineering and scientific applications.
 Simulink: A MATLAB-based environment for modeling, simulating, and analyzing
multidomain dynamical systems.
3

4. Form-Based Programming:
o Overview: Form-based programming is a visual approach where developers design software
by creating and arranging forms. Each form represents a screen or dialog box in the
application, and the development environment generates the underlying code.
o Examples:
 Microsoft Access: A database management system that uses a form-based interface to
create and manage databases.
 Delphi: An IDE that uses form-based programming for building Windows applications.
5. Model-Driven Development (MDD):
o Overview: MDD focuses on creating and exploiting domain models, which are conceptual
models of the domain that describe the structure and behavior of the application. Visual tools
allow developers to create models that generate code automatically.
o Examples:
 UML Tools: Tools like Enterprise Architect use Unified Modeling Language (UML)
diagrams to model the software and generate code.
 Out Systems: A low-code platform that uses model-driven development to create
enterprise applications.
6. Node-Based Programming:
o Overview: Node-based programming represents program logic as a graph of interconnected
nodes. Each node performs a specific task, and the connections between nodes define the flow
of data or control.
o Examples:
 Unreal Engine Blueprint: A visual scripting system for the Unreal Engine, allowing
game developers to create gameplay elements without writing code.
 Blender's Node Editor: Used for creating materials, shaders, and compositing effects in
3D modeling and animation.

1.3. Rapid Application Development (RAD) Tools and Techniques


Overview of Rapid Application Development (RAD)
Rapid Application Development (RAD) is a software development methodology that
emphasizes rapid delivery of working software. It focuses on iterative development, prototyping, and
early user feedback to accelerate the development process. RAD focuses on minimizing planning and
design time, allowing for faster development and adjustment to changing requirements.
Key Principles of RAD:
 User Involvement: End-users are heavily involved throughout the development process,
providing feedback and ensuring the final product meets their needs.
 Iterative Development: The development process is broken down into smaller segments or
iterations, each resulting in a working prototype allowing for continuous feedback and
improvements.
 Component Reusability: RAD encourages the reuse of pre-existing software components to
speed up development.
 Flexibility and Adaptability: The process is flexible, allowing changes to be made at any stage
based on user feedback or new requirements.
 Prototyping: Creating early versions of the application to gather feedback and refine requirements.
 Teamwork: RAD often involves cross-functional teams working together to deliver the
application quickly.

Benefits of RAD:
 Faster Time-to-Market: By focusing on rapid development and iterative cycles, RAD can
significantly reduce the time it takes to deliver a working product.
 Reduced Risk: Early prototyping allows for issues to be identified and addressed sooner.
4

 Improved User Satisfaction: Early user feedback and prototyping help ensure that the final
product meets the needs and expectations of the users.
 Reduced Costs: The reuse of components and faster development can lead to lower overall costs.
RAD can help reduce development costs by minimizing rework and avoiding unnecessary
features.
 Increased Flexibility: The iterative nature of RAD allows for flexibility to adapt to changing
requirements or market conditions.

RAD Tools and Techniques


Several tools and techniques are designed to support the RAD methodology by enabling rapid
prototyping, iterative development, and user-centered design.
1. Visual Studio (WinForms and WPF)
o Description: Microsoft Visual Studio is a comprehensive IDE that supports RAD through
features like drag-and-drop interface design, integrated debugging, and a vast library of pre-
built components. With WinForms and WPF (Windows Presentation Foundation), developers
can quickly design and build desktop applications.
o Use Case: Building Windows desktop applications with a focus on rapid development and
iterative design.
2. Delphi
o Description: Delphi is an IDE for rapid development of desktop, mobile, and web
applications. It uses the Object Pascal programming language and provides a visual design
interface for creating applications.
o Use Case: Ideal for building cross-platform applications that require a rich user interface and
database connectivity.
3. OutSystems
o Description: OutSystems is a low-code platform that enables rapid development of enterprise
applications. It provides visual development tools, pre-built templates, and components to
accelerate the development process.
o Use Case: Suitable for enterprise-level applications that need to be developed quickly with
integration into existing IT systems.
4. FileMaker Pro
o Description: FileMaker Pro is a cross-platform relational database application that allows
users to create custom apps without extensive programming knowledge. It offers a visual
interface for designing databases and forms.
o Use Case: Developing custom business applications, particularly those that require database
management and reporting.
5. AppGyver
o Description: AppGyver is a low-code/no-code platform that allows for rapid development of
web and mobile applications. It provides a visual interface for designing apps without writing
code.
o Use Case: Creating mobile and web applications quickly, particularly when traditional coding
is not required.
6. Oracle APEX (Application Express)
o Description: Oracle APEX is a low-code development platform for building web applications
on top of Oracle databases. It is especially useful for data-driven applications and comes with
various tools to facilitate rapid development.
o Use Case: Developing web applications that are tightly integrated with Oracle databases.

Techniques in RAD
1. Prototyping: Prototyping involves creating a preliminary version of the software application,
which is then iteratively refined based on user feedback. This technique allows developers to test
concepts, gather requirements, and refine the application's design and functionality.
5

2. Component-Based Development: This technique involves developing software by assembling


pre-existing components or modules. By reusing these components, developers can reduce
development time and focus on the unique aspects of the application.
3. Timeboxing: Timeboxing involves setting a fixed time period for developing a particular feature
or iteration. This approach helps in managing project scope and ensuring that the development
process remains focused and within schedule.
4. Iterative Development: Iterative development involves breaking the project into smaller
segments or iterations, with each iteration resulting in a working prototype. This allows for
continuous feedback and refinement throughout the development process.
5. Joint Application Development (JAD): JAD sessions involve structured meetings with
stakeholders, developers, and users to collaboratively define requirements and design the system.
This technique ensures that the final product aligns closely with user needs.

1.4. Event driven programming paradigm and C#


Event-Driven Programming is a programming paradigm where the flow of control is
determined by events, such as button clicks, mouse movements, or keystrokes. In this model, the
program waits for events to occur and then executes specific code in response to those events. In this
model, events trigger the execution of specific sections of code, called event handlers.

Key Characteristics of Event-Driven Programming:


 Events: Actions or occurrences that happen in the system (e.g., button clicks, data updates) that
the program responds to.
 Event Listeners: Objects or methods that are registered to listen for specific events.
 Event Handlers: Functions or methods that are executed when an event occurs.
 Event Queues: Structures that store events that have occurred but have not yet been processed.
 Asynchronous Execution: Event-driven programs can often execute asynchronously, allowing
multiple tasks to be processed simultaneously.

C# and Event-Driven Programming:


C# is well-suited for event-driven programming, providing a rich set of features and syntax for handling
events. Here are some key aspects of event-driven programming in C#:
 Delegates: Delegates are types that represent methods. They are used to define event signatures
and to associate event handlers with events.
 Events: Events are declared using the event keyword and are typically associated with classes or
objects.
 Event Handlers: Event handlers are methods that are registered to handle specific events. They
must have a signature that matches the delegate type associated with the event.
 Event Subscription: To subscribe an event handler to an event, you use the += operator. To
unsubscribe, you use the -= operator.
Example:
using System;
using System.Windows.Forms;

namespace EventDrivenExample
{
public partial class Form1 : Form
{
public Form1()
{
6

InitializeComponent();

// Event handler for button click


button1.Click += Button1_Click;
}

private void Button1_Click(object sender, EventArgs e)


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

In this example:
1. A Button control is created and associated with a Button1_Click event handler.
2. When the button is clicked, the Button1_Click method is executed, displaying a message box.

Example 2 of Event-Driven Programming in C#


Let’s create a simple Windows Forms application in C# to demonstrate the event-driven programming
paradigm.

using System;
using System.Windows.Forms;

public class MainForm : Form


{
private Button button1;

public MainForm()
{
// Initialize the button
button1 = new Button();
button1.Text = "Click Me!";
button1.Location = new System.Drawing.Point(50, 50);

// Attach the event handler to the button's Click event


button1.Click += new EventHandler(Button1_Click);

// Add the button to the form


Controls.Add(button1);
}

// Event handler for button click


private void Button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button clicked!");
}
7

[STAThread]
public static void Main()
{
// Run the application
Application.Run(new MainForm());
}
}

Output Sample

Explanation:
 MainForm Class: This class inherits from Form, which represents a window or dialog box in a
Windows Forms application.
 Button Initialization: A Button control is created, and its properties like Text and Location are set.
 Event Subscription: The Click event of the button is wired to the Button1_Click event handler
using the += operator. This means when the button is clicked, the Button1_Click method will be
executed.
 Event Handler: The Button1_Click method is defined to show a message box when the button is
clicked.

Key Points:
 The Click event is an example of an event in C#. It is triggered when the user clicks the button.
 The Button1_Click method is the event handler that responds to the Click event.
 Events in C# are managed using delegates, ensuring that the event handler signature matches the
expected method signature for the event.

Common Use Cases in C# Event-Driven Programming:


1. GUI Applications: C# is widely used for developing Windows desktop applications with GUIs,
where event-driven programming is essential. User interactions, such as clicking buttons, entering
text, or moving the mouse, all generate events that the application responds to.
2. Web Applications (ASP.NET): In web applications built with ASP.NET, events such as button
clicks, page loads, and form submissions are handled by event-driven code. The event handlers
manage server-side logic that processes user inputs and interactions.
3. Game Development: Game engines like Unity use C# for scripting, where event-driven
programming is crucial. Player inputs, collision detection, and other game events are managed
using this paradigm.
8

4. IoT Applications: In Internet of Things (IoT) applications, sensors and devices generate events
that trigger actions or data processing. C# can be used to build event-driven IoT applications,
especially when using .NET-based frameworks.

1.5. .NET Features, programming model and Architecture


Overview of .NET
.NET is a comprehensive, cross-platform, open-source developer platform created by Microsoft. It is
designed for building a wide variety of applications, including web, desktop, mobile, gaming, and IoT.
The .NET platform provides a consistent programming model, a rich set of libraries, and the ability to
interoperate across different languages.

Key Features of .NET


 Common Language Runtime (CLR): The foundation of .NET, providing memory management,
garbage collection, type safety, and language interoperability.
 Base Class Library (BCL): A rich collection of classes for common programming tasks,
including file I/O, networking, data access, and more.
 Language Interoperability: Enables seamless integration of different .NET languages within the
same application.
 Assembly Management: Manages the deployment, versioning, and security of .NET applications.
 Cross-Platform Compatibility: .NET Core and .NET 5+ offer support for various platforms,
including Windows, macOS, Linux, and mobile devices.
 Cloud Integration: Strong integration with cloud platforms like Azure, AWS, and GCP for
building cloud-native applications.
 Asynchronous Programming: Supports asynchronous programming models for non-blocking
operations and improved performance.

Programming Model:
 Object-Oriented: .NET follows an object-oriented paradigm, emphasizing encapsulation,
inheritance, and polymorphism.
 Type Safety: Ensures strong type checking at compile time to prevent common programming
errors.
 Garbage Collection: Automatically manages memory allocation and deallocation, reducing the
risk of memory leaks.
 Generics: Provides type safety and code reusability through parameterized types.
 Linq: A powerful query language for working with collections and data sources.

Architecture:
 Layered Architecture: .NET applications often follow a layered architecture, separating
concerns into distinct layers:
o Presentation Layer: Handles the user interface and interaction.
o Business Logic Layer: Implements the core functionality and business rules.
o Data Access Layer: Interacts with databases or other data storage mechanisms.
 Model-View-Controller (MVC): A popular architectural pattern that separates the application
into Model (data), View (user interface), and Controller (logic) components.
 Dependency Injection: A design pattern that promotes loose coupling between components,
making code more testable and maintainable.

.NET Application Development Example


Here’s a basic example of a .NET Core console application:
9
using System;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// This is a simple .NET Core console
application Console.WriteLine("Hello, World!");
}
}
}

Explanation:
 Namespace: HelloWorld is the namespace that encapsulates the application’s code, helping to
organize it.
 Class: Program is the main class that contains the entry point of the application.
 Main Method: static void Main(string[] args) is the entry point of the application, where the
execution starts.
 Console.WriteLine: This is a method from the .NET Base Class Library that outputs a string to
the console.

Example 2:
using System;

namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
// Create an instance of a class
Person person = new Person("Alice", 30);

// Access properties and methods


Console.WriteLine(person.Name);
person.Age = 31;
Console.WriteLine(person.Age);

// Use LINQ to query a collection


List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 ==
0); foreach (int number in evenNumbers)
{
Console.WriteLine(number);
}
}
}
10
class Person
{
public string Name { get; set; }
public int Age { get; set; }

public Person(string name, int age)


{
Name = name;
Age = age;
}
}
}

1.6. Environment and IDE Setup and Configuration: Visual Studio and VS Code
Overview
Setting up the development environment and configuring your Integrated Development Environment
(IDE) is crucial for a smooth development experience in .NET. Visual Studio and Visual Studio Code
(VS Code) are the two most popular IDEs for .NET development, each with its own strengths and use
cases.

Visual Studio Setup and Configuration


Visual Studio is a comprehensive and feature-rich IDE primarily used for large-scale .NET projects,
including desktop applications, web applications, cloud services, and more. It offers advanced tools for
debugging, testing, and deployment.
Steps to Set Up Visual Studio:
1. Download and Install Visual Studio:
o Visit the Visual Studio website and download the installer for the latest version of Visual Studio.
o Run the installer and choose the workloads that match your development needs. For .NET
development, you might choose:
 ASP.NET and web development for web applications.
 .NET desktop development for Windows Forms, WPF, and console applications.
 Azure development for cloud-based applications.
 Mobile development with .NET for Xamarin applications.
2. Choose Development Workloads:
o During installation, Visual Studio allows you to select workloads that cater to different types
of development. For example:
 .NET Core cross-platform development: For building .NET Core applications.
 ASP.NET and web development: For web applications using ASP.NET Core or
ASP.NET MVC.
 Azure development: For integrating your .NET projects with Microsoft Azure.
3. Configure the IDE:
o After installation, launch Visual Studio and configure the IDE settings.
o Theme and Layout: Choose your preferred theme (light, dark, or blue) and customize the
layout according to your preferences.
o Account Integration: Sign in with your Microsoft account to sync settings across devices and
access Azure services.
o Extensions: Install extensions from the Visual Studio Marketplace to enhance your
development experience. Popular extensions include:
 ReSharper: For code analysis and refactoring.
11

 Azure Tools: For managing Azure resources directly from the IDE.
 GitHub Extension: For integrating with GitHub repositories.
4. Create a New Project:
o To start a new project, go to File > New > Project.
o Select the project template based on the type of application you want to build, such as
Console App (.NET Core), ASP.NET Core Web Application, or WPF App.
o Configure the project settings (name, location, framework) and click Create.
5. Build and Run:
o After setting up your project, you can write your code in the editor.
o Use the F5 key to build and run the project with debugging, or Ctrl+F5 to run without
debugging.
o Visual Studio provides a powerful debugger, allowing you to set breakpoints, step through
code, and inspect variables.
6. Version Control:
o Visual Studio integrates with Git, allowing you to manage source control directly within the
IDE.
o You can clone repositories, commit changes, and push updates to remote repositories using
the integrated Git tools.

Visual Studio Code Setup and Configuration


Visual Studio Code (VS Code) is a lightweight, cross-platform code editor that supports a wide
range of programming languages and frameworks. It is highly customizable and is popular for web
development, scripting, and smaller .NET projects.
Steps to Set Up Visual Studio Code:
1. Download and Install VS Code:
o Visit the VS Code website and download the version suitable for your operating system
(Windows, macOS, or Linux).
o Run the installer and complete the installation process.
2. Install .NET SDK:
o Before you can develop .NET applications in VS Code, you need to install the .NET SDK.
o Download the .NET SDK from the Microsoft .NET website.
o Follow the installation instructions for your operating system.
3. Install C# Extension:
o Launch VS Code and navigate to the Extensions view by clicking the Extensions icon in the
Activity Bar or pressing Ctrl+Shift+X.
o Search for the "C#" extension by Microsoft and install it. This extension provides language
support, IntelliSense, and debugging capabilities for C#.
4. Configure VS Code:
o Settings: Access the settings via File > Preferences > Settings or press Ctrl+,. You can
customize the editor's appearance, behavior, and keyboard shortcuts.
o Themes and Icons: Install additional themes and icon packs from the Extensions
Marketplace to personalize your workspace.
o Keybindings: Customize keybindings or use pre-defined keybinding profiles, like Visual
Studio or Sublime Text, to match your preferred workflow.
5. Create a New Project:
o Open a terminal in VS Code by pressing Ctrl+ or using the menu Terminal > New Terminal.
o Navigate to the folder where you want to create your project.
o Use the .NET CLI to create a new project:
12

dotnet new console -n MyConsoleApp


oThis command creates a new console application in a folder named MyConsoleApp.
6. Build and Run:
o Open the project folder in VS Code by using File > Open Folder.
o You can build and run the application directly from the terminal using:

dotnet build
dotnet run
o Alternatively, use the Run and Debug view to configure debugging. VS Code will prompt
you to create a launch.json file for debugging configuration.
7. Extensions and Integrations:
o VS Code has a rich ecosystem of extensions. Some useful ones for .NET development include:
 NuGet Package Manager: For managing NuGet packages within your project.
 Azure Tools: For integrating with Azure services.
 GitLens: For advanced Git features and visualization.
 Docker: For containerizing your .NET applications.
8. Version Control:
o VS Code has built-in Git support. You can view changes, stage commits, and manage
branches from the Source Control view.
o Extensions like GitHub Pull Requests and Issues allow you to manage pull requests and issues
directly from VS Code.

Choosing Between Visual Studio and VS Code


 Visual Studio: Best suited for large, complex projects that require extensive tooling, such as
enterprise applications, desktop applications, or cloud services.
 VS Code: Ideal for lightweight, cross-platform development, scripting, web development, and
smaller projects.
Both IDEs are powerful tools for .NET development, and your choice will depend on your specific
needs and workflow preferences.
13

Unit 2
C# Language Basics

2.1. Data Types and namespaces


Data Types
In C#, data types define the type of data that can be stored in a variable. They are broadly
classified into two categories:
1. Value Types
2. Reference Types

1. Value Types
Value types hold the data directly. Common examples include:
 int: Stores integers.
 float: Stores single-precision floating-point numbers.
 double: Stores double-precision floating-point numbers.
 char: Stores a single character.
 bool: Stores a Boolean value (true or false).
 struct: A composite value type that can contain variables of different types.
 enum: A distinct type consisting of a set of named constants.

Common Value Types:


int age = 25; // Integer type
float price = 19.99f; // Floating point type
char grade = 'A’; // Character type
bool isLoggedIn = true; // Boolean type

2. Reference Types
Reference types store the reference (or address) to the actual data. Common examples include:
 string: A sequence of characters.
 array: A collection of elements of the same type.
 class: A blueprint for creating objects.
 interface: A contract that defines a set of methods and properties.
 delegate: A reference type that holds a reference to a method.

Common Reference Types:


string name = "John Doe"; // String type (sequence of characters)
int[] numbers = { 1, 2, 3, 4, 5 }; // Array of integers

Namespaces
Namespaces in C# are used to organize code and prevent name collisions. They provide a way to
group related classes, structs, enums, delegates, and interfaces together.
 The System namespace is the root of many base namespaces in .NET.
 You can define your own namespaces to organize your code.
14

Example: Using Data Types and Namespaces:


using System;

namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
int number = 10;
double decimalNumber =
3.14; bool isTrue = true;
char character = 'A';

Console.WriteLine(number);
Console.WriteLine(decimalNumber);
Console.WriteLine(isTrue);
Console.WriteLine(character);
}
}
}

2.2. Type Conversion


Type conversion in C# is the process of converting a value from one data type to another. C#
supports two types of type conversion:
1. Implicit Conversion: Automatically performed by the compiler when converting from a smaller
to a larger data type, or when no data will be lost.
2. Explicit Conversion (Casting): Requires a cast operator and is used when converting from a
larger to a smaller data type or between incompatible data types.

Implicit Conversion
Implicit conversion is safe and doesn’t require special syntax. It occurs when the conversion is
guaranteed not to cause data loss.
Implicit Conversion Example:
int myInt = 10;
double myDouble = myInt; // Implicit conversion from int to double

Explicit Conversion (Casting)


Explicit conversion requires the use of a cast operator. This type of conversion is used when
converting from a larger data type to a smaller one or between incompatible data types.
Explicit Conversion Example:
double myDouble = 9.78;
int myInt = (int)myDouble; // Explicit conversion from double to int (results in 9)

Conversion Using the Convert Class


15

C# also provides the Convert class for converting between different types. This class offers various
methods like Convert.ToInt32(), Convert.ToDouble(), Convert.ToString(), etc.
Code Example:
string myString = "123";
int myInt = Convert.ToInt32(myString); // Converts string to int

2.3. Flow controls: Looping and iterations


Flow control in C# allows you to direct the order in which statements are executed. Looping and
iteration are fundamental concepts used to repeatedly execute a block of code based on a condition or
through a collection of elements.
In C#, there are several types of loops:
1. for Loop
2. while Loop
3. do-while Loop
4. foreach Loop

1. for Loop
The for loop is used when the number of iterations is known beforehand. It repeats a block of code
a specific number of times.
Syntax:
for (initialization; condition; increment)
{
// Code to be executed
}

Code Example: Output


using System; For Loop
Example: Iteration:
namespace ForLoopExample 1
{ Iteration: 2
class Program Iteration: 3
{
Iteration: 4
static void Main(string[] args)
{ Iteration: 5
Console.WriteLine("For Loop Example:");

for (int i = 1; i <= 5; i++)


{
Console.WriteLine("Iteration: " + i);
}
}
}
}
16

2. while Loop
The while loop is used when the number of iterations is not known beforehand. It continues to
execute a block of code as long as a specified condition is true.
Syntax:
while (condition)
{
// Code to be executed
}

Code Example: Output


using System;

namespace WhileLoopExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("While Loop Example:");

int i = 1;
while (i <=
5) While
{
Console.WriteLine("Iteration: " +
i); i++;
}
}
}
}

3. do-while Loop
The do-while loop is similar to the while loop, but it checks the condition after executing the loop
body. This ensures that the loop body is executed at least once.
Syntax:
do
{ Loop
// Code to be executed
} while (condition);

Code Example:
using System;

namespace DoWhileLoopExample
{
class Program
{
17

Output
static void Main(string[] args)
{ Do-While Loop
Console.WriteLine("Do-While Loop Example:"); Example: Iteration: 1
Iteration: 2
int i = 1; Iteration: 3
do Iteration: 4
{ Iteration: 5
Console.WriteLine("Iteration: " +
i); i++;
} while (i <= 5);
}
}
}

4. foreach Loop
The foreach loop is specifically used to iterate through the elements of a collection (like an array or
a list). It is particularly useful when you don't need to modify the collection while iterating over it.
Syntax:
foreach (type variable in collection)
{
// Code to be executed
}

Code Example:
using System;

namespace ForeachLoopExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Foreach Loop Example:");

string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry"

}; foreach (string fruit in fruits)


{
Console.WriteLine("Fruit: " + fruit);
}
}
}
}
18

Output:

Foreach Loop
Example: Fruit: Apple
Fruit: Banana
Fruit: Cherry
Fruit: Date
Fruit:
Elderberry
Combining Loops with Conditional Statements
You can also combine loops with conditional statements to control the flow based on specific
conditions.

Code Example: Output

using System; Loop with Condition


Example: 1 is odd.
namespace LoopWithConditionExample 2 is even.
{ 3 is odd.
class Program 4 is even.
{ 5 is odd.
static void Main(string[] args)
6 is even.
{
7 is odd.
Console.WriteLine("Loop with Condition Example:");
8 is even.
for (int i = 1; i <= 10; i++) 9 is odd.
{ 10 is even.
if (i % 2 == 0)
{
Console.WriteLine(i + " is even.");
}
else
{
Console.WriteLine(i + " is odd.");
}
}
}
}
}

2.4. Arrays
Arrays in C# are ordered collections of elements of the same type.
Arrays in C# are used to store multiple values of the same type in a single variable. An array is a
collection of elements stored in a contiguous memory location, and each element can be accessed
using an index.
1. Declaring and Initializing Arrays
You can declare an array by specifying the type of its elements followed by square brackets. You
can also initialize the array with values at the time of declaration.
19

Code Example:
using System;

namespace ArrayExample
{
class Program
{
static void Main(string[] args)
{
// Declaring and initializing an array
int[] numbers = { 10, 20, 30, 40, 50 };

Console.WriteLine("Array Elements:");

// Accessing array elements using a for loop


for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("Element at index " + i + ": " + numbers[i]);
}
}
}
}

Output:
Array Elements:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

2. Accessing and Modifying Array Elements


You can access and modify array elements using their index. The index of the first element in an
array is 0, and the last element is Length - 1.
Code Example:
using System;

namespace AccessModifyArray
{
class Program
{
static void Main(string[] args)
{
// Declaring and initializing an
array string[] fruits = new string[3];
fruits[0] = "Apple";
fruits[1] =
"Banana"; fruits[2]
= "Cherry";
20

Console.WriteLine("Original Array:"); Output


Original Array:
foreach (string fruit in fruits) Apple
{ Banana
Console.WriteLine(fruit); Cherry
}
Modified Array:
// Modifying an element
Apple
fruits[1] = "Blueberry";
Blueberry
Console.WriteLine("\nModified Cherry
Array:"); foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}
}

3. Multidimensional Arrays
C# supports multidimensional arrays, which are arrays of arrays. The most common
multidimensional array is the two-dimensional array, which can be thought of as a matrix or table.
Code Example: Output

using System; 2D Array (Matrix):


namespace MultidimensionalArrayExample 123
{ 456
class Program 789
{
static void Main(string[] args)
{
// Declaring and initializing a 2D array (3x3 matrix)
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Console.WriteLine("2D Array (Matrix):");

// Accessing elements of a 2D array


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
21

4. Jagged Arrays
A jagged array is an array of arrays, where each inner array can have a different size. Unlike
multidimensional arrays, jagged arrays are not required to have uniform dimensions.

Code Example: Output

using System; Jagged Array:


namespace JaggedArrayExample Element at index 0: 1 2
{ Element at index 1: 3 4 5
class Program Element at index 2: 6 7 8 9
{
static void Main(string[] args)
{
// Declaring and initializing a jagged array
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

Console.WriteLine("Jagged Array:");

// Accessing elements of a jagged array


for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write("Element at index " + i + ": ");
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
}
}
}

5. Array Methods
C# provides several methods to perform operations on arrays, such as sorting, reversing, and
finding elements.
Code Example:
using System;

namespace ArrayMethodsExample
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 5, 2, 9, 1, 5, 6 };
22

Console.WriteLine("Original Array:"); Output


foreach (int number in numbers)
{ Original Array:
Console.Write(number + " "); 529156
}
Sorted Array:
// Sorting the array 125569
Array.Sort(numbers);
Console.WriteLine("\n\nSorted Array:");
Reversed Array:
foreach (int number in numbers)
{ 965521
Console.Write(number + " ");
} Index of element '9': 0

// Reversing the array


Array.Reverse(numbers);
Console.WriteLine("\n\nReversed
Array:"); foreach (int number in numbers)
{
Console.Write(number + " ");
}

// Finding an element in the array


int index = Array.IndexOf(numbers, 9);
Console.WriteLine("\n\nIndex of element '9': " +
index);
}

2.5. Structures, Enumerations


Structures in C#
Structures in C# are value types that can contain multiple related data items. They are similar to
classes but are generally used for smaller, lightweight objects that do not require inheritance.
Defining a Structure
A structure is defined using the struct keyword. It can contain fields, methods, constructors, properties,
and events.
Code Example:
using System;

namespace StructExample
{
// Define a structure
struct Book
{
public string Title;
public string Author;
public int Year;

// Constructor
public Book(string title, string author, int year)
{
23
Title = title;
Author =
author; Year =
year;
}

// Method to display book details


public void DisplayInfo()
{
Console.WriteLine($"Title: {Title}, Author: {Author}, Year: {Year}");
}
}

class Program
{
static void Main(string[] args)
{
// Create an instance of the Book struct
Book book1 = new Book("1984", "George Orwell", 1949);

// Access and modify fields


book1.Title = "Animal Farm";
book1.Author = "George
Orwell"; book1.Year = 1945;

// Display book information


book1.DisplayInfo();

// Another way to create an instance


Book book2;
book2.Title = "Brave New
World"; book2.Author = "Aldous
Huxley"; book2.Year = 1932;

// Display book information


book2.DisplayInfo();
}
}
}
Output:
Title: Animal Farm, Author: George Orwell, Year: 1945
Title: Brave New World, Author: Aldous Huxley, Year:
1932
Key Points about Structures:
 Value Type: Structures are value types, meaning they are stored on the stack, not the heap.
 No Inheritance: Structures do not support inheritance.
 Default Constructor: Unlike classes, structures cannot have a parameterless constructor.
However, C# provides a default constructor that initializes all fields to their default values.
24

Output:

Enumerations in C#
Enumerations, or enums, are special data types that allow a variable to be a set of predefined
constants. They make your code more readable and manageable by replacing numeric constants with
descriptive names.
Defining an Enumeration
Enumerations are defined using the enum keyword, and each member of the enum is associated with
an integer value, starting from 0 by default.

Code Example:
using System;

namespace EnumExample
{
// Define an enumeration for days of the week
enum DayOfWeek
{
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
}

class Program
{
static void Main(string[] args)
{
// Assign an enum value to a variable
DayOfWeek today = DayOfWeek.Friday;

// Print the enum value


Console.WriteLine("Today is: " + today); // Outputs: Today is: Friday

// Convert enum to integer


int dayNumber = (int)today;
Console.WriteLine("Day number: " + dayNumber); // Outputs: Day number: 5

// Loop through all enum values


Console.WriteLine("\nDays of the week:");
foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek)))
{
Console.WriteLine(day + " = " + (int)day);
}
}
}
}
25

Output:

Today is:
Friday Day
number: 5

Days of the
week: Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
Key Points about Enumerations:
 Strongly Typed: Enums are strongly typed constants. An enum variable can only be assigned one
of the predefined enum constants.
 Underlying Type: The default underlying type of the elements in the enum is int, but you can
specify another integral type (e.g., byte, short, long).
 Custom Values: You can assign custom integer values to enum members.

Example: Custom Values in Enum


using System;

namespace CustomEnumExample
{
// Define an enumeration with custom values
enum Severity
{
Low = 1,
Medium = 5,
High = 10,
Critical = 15
}

class Program
{
static void Main(string[] args)
{
// Assign and display a custom enum value
Severity level = Severity.High;
Console.WriteLine("Severity Level: " + level); // Outputs: Severity Level: High
Console.WriteLine("Severity Value: " + (int)level); // Outputs: Severity Value:
10
}
}
}
26

Output:
Severity Level:
High Severity
Value: 10
2.6. Strings, Regular Expressions and Collections
1. Strings in C#
Strings in C# are sequences of characters used to represent text. The string type is an alias for
System.String and is immutable, meaning once a string object is created, it cannot be changed.
String Operations
You can perform various operations on strings, such as concatenation, comparison, searching, and
more.
Code Example:
using System;

namespace StringExample
{
class Program
{
static void Main(string[] args)
{
string firstName = "John";
string lastName = "Doe";

// String concatenation
string fullName = firstName + " " + lastName;
Console.WriteLine("Full Name: " + fullName);

// String length
Console.WriteLine("Length of Full Name: " + fullName.Length);

// String comparison
bool areEqual = firstName.Equals(lastName);
Console.WriteLine("Are First Name and Last Name equal? " + areEqual);

// String substring
string substring = fullName.Substring(0, 4);
Console.WriteLine("Substring of Full Name: " + substring);

// String replace
string replacedString = fullName.Replace("John", "Jane");
Console.WriteLine("Replaced String: " + replacedString);

// String to Upper Case


Console.WriteLine("Upper Case: " + fullName.ToUpper());

// String to Lower Case


Console.WriteLine("Lower Case: " + fullName.ToLower());
}
}
}
27

Output:
Full Name: John Doe
Length of Full Name:
8
Are First Name and Last Name equal?
False Substring of Full Name: John
Replaced String: Jane
Doe Upper Case: JOHN
DOE Lower Case: john
2. Regular Expressions in C#
Regular expressions (regex) are used to define patterns for matching strings. C# provides the
System.Text.RegularExpressions namespace for working with regular expressions.

Basic Regex Operations


You can use regular expressions to search, replace, and split strings.
Code Example:
using System;
using System.Text.RegularExpressions;

namespace RegexExample
{
class Program
{
static void Main(string[] args)
{
string input = "The quick brown fox jumps over the lazy dog.";

// Pattern to match words


string pattern = @"\b\w+\b";

// Find all matches


MatchCollection matches = Regex.Matches(input, pattern);
Console.WriteLine("Words found in input string:");
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}

// Replace words with uppercase version


string result = Regex.Replace(input, pattern, m => m.Value.ToUpper());
Console.WriteLine("\nString after replacement: " + result);

// Check if input matches a pattern


string pattern2 = @"^\d{3}-\d{2}-\d{4}$"; // Pattern for SSN format
string ssn = "123-45-6789";
bool isMatch = Regex.IsMatch(ssn, pattern2);
Console.WriteLine("\nIs the SSN valid? " + isMatch);
}
}
}
Prepared by Mukesh Singh, Sanothimi MICTE (2079/2023 Batch)
28

Output:
Words found in input string:
The
quick
brown
fox
jumps
over
the
lazy
dog

String after replacement: THE QUICK BROWN FOX JUMPS OVER THE LAZY

DOG. Is the SSN valid? True

3. Collections in C#
Collections in C# are used to store groups of related objects. The .NET Framework provides
several types of collections, including arrays, lists, dictionaries, and more. Collections are found in
the System.Collections and System.Collections.Generic namespaces.
Commonly Used Collections
1. List<T>: A generic collection that can store elements of a specific type.
2. Dictionary<TKey, TValue>: A collection that stores key-value pairs.
3. Queue<T>: A collection that represents a first-in, first-out (FIFO) queue.
4. Stack<T>: A collection that represents a last-in, first-out (LIFO) stack.

Code Example:
using System;
using System.Collections.Generic;

namespace CollectionsExample
{
class Program
{
static void Main(string[] args)
{
// List<T>
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
fruits.Add("Date");
Console.WriteLine("List of
Fruits:"); foreach (string fruit in
fruits)
{
Console.WriteLine(fruit);
}
29

Output
// Dictionary<TKey, TValue> List of
Dictionary<int, string> students = new Dictionary<int, Fruits: Apple
string>(); students.Add(1, "John"); Banana
students.Add(2, "Jane"); Cherry
students.Add(3, "Jim"); Console.WriteLine("\ Date
nDictionary of Students:"); foreach (KeyValuePair<int,
string> student in students)
Dictionary of
{
Students: ID: 1, Name:
Console.WriteLine("ID: " + student.Key + ", Name: " + student.Value);
} John
ID: 2, Name:
// Queue<T> Jane ID: 3,
Queue<string> queue = new Name: Jim
Queue<string>(); queue.Enqueue("First");
queue.Enqueue("Second"); Queue Elements:
queue.Enqueue("Third"); First
Console.WriteLine("\nQueue Elements:"); Second
while (queue.Count > 0) Third
{
Console.WriteLine(queue.Dequeue()); Stack
}
Elements:
// Stack<T> Third
Stack<string> stack = new
Stack<string>(); stack.Push("First");
stack.Push("Second");
stack.Push("Third");
Console.WriteLine("\nStack
Elements:"); while (stack.Count > 0)
{
Console.WriteLine(stack.Pop());
}
}
}
}
30

Unit 3
Object Oriented Concepts in C#

3.1. OOP Structure, Class and Object


Object-Oriented Programming (OOP) Structure
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects,"
which can contain data and code: data in the form of fields (often known as properties), and code in
the form of procedures (often known as methods).

Four Pillars of OOP:


1. Encapsulation: Bundling the data (attributes) and methods (functions) that operate on the data
into a single unit or class. It also restricts direct access to some of an object's components, which
is a means of preventing accidental interference and misuse of the data.
2. Abstraction: Hiding the complex reality while exposing only the essential parts. It's about
creating a simple interface that exposes only what is necessary and hides the implementation
details.
3. Inheritance: The mechanism by which one class can inherit the properties and methods of
another class. This promotes code reusability.
4. Polymorphism: The ability to process objects differently depending on their data type or class. It
allows one interface to be used for a general class of actions.

Class and Object


Class:
 A class is a blueprint for creating objects. It defines a datatype by bundling data and methods that
work on the data into one single unit.
 In C#, class is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.

Let's see an example of C# class that has two fields only.


public class Student
{
int id;//field or data member
String name;//field or data
member
}
Object:
 An object is an instance of a class. When a class is defined, no memory is allocated until an object
of that class is created.
 In C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
 In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.
 Object is a runtime entity; it is created at runtime.
 Object is an instance of a class. All the members of the class can be accessed through object.

Let's see an example to create object using new keyword.


Student s1 = new Student(); //creating an object of Student
In this example, Student is the type and s1 is the reference variable that refers to the instance of
31
Student class. The new keyword allocates memory at runtime.
32

C# Object and Class Example 1


Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.
Output
using System;
101
public class Student
{ Sonoo Jaiswal
int id;//data member (also instance variable)
String name;//data member(also instance
variable)

public static void Main(string[] args)


{
Student s1 = new Student();//creating an object of Student

s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);

}
}

C# Class Example 2: Having Main() in another class


Let's see another example of class where we are having Main() method in another class. In such
case, class must be public.
Output
using System;
public class Student 101
{
public int id; Sonoo Jaiswal
public String name;
}
class TestStudent{
public static void Main(string[] args)
{
Student s1 = new Student();
s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);

}
}
33

3.2. Method Overloading, Method Overriding


1. Method Overloading
 Having two or more methods with same name but different in parameters, is known as method
overloading in C#.
 Method overloading is a feature that allows a class to have multiple methods with the same
name but different parameters (i.e., different types, number of parameters, or both). This allows
the same method name to perform different tasks based on the input provided.
 The advantage of method overloading is that it increases the readability of the program
because you don't need to use different names for same action.
You can perform method overloading in C# by two ways:
1. By changing number of arguments
2. By changing data type of the arguments

C# Method Overloading Example: By changing no. of arguments


Let's see the simple example of method overloading where we are changing number of arguments
of add() method.
Output:
using System;
public class Cal{ 35
public static int add(int a,int b){ 60
return a + b;
}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}
public class TestMemberOverloading
{
public static void Main()
{
Console.WriteLine(Cal.add(12, 23));
Console.WriteLine(Cal.add(12, 23, 25));
}
}

C# Method Overloading Example: By changing data type of arguments


Let's see the another example of method overloading where we are changing data type of
arguments.
using System; Output
public class Cal{
35
public static int add(int a, int b){
return a + b; 33.7
}
public static float add(float a, float b)
{
return a + b;
}
}
33 public class TestMemberOverloading
{
public static void Main()
{
Console.WriteLine(Cal.add(12, 23));
Console.WriteLine(Cal.add(12.4f,21.3f));
}
}

2. Method Overriding
 If derived class defines same method as defined in its base class, it is known as method
overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide
specific implementation of the method which is already provided by its base class.
 To perform method overriding in C#, you need to use virtual keyword with base class method
and override keyword with derived class method.

Example of Method Overriding in C#:


Let's see a simple example of method overriding in C#. In this example, we are overriding the eat()
method by the help of override keyword.
using System; Output
public class Animal{ Eating bread...
public virtual void eat(){
Console.WriteLine("Eating...");
}
}
public class Dog: Animal
{
public override void eat()
{
Console.WriteLine("Eating bread...");
}
}
public class TestOverriding
{
public static void Main()
{
Dog d = new Dog();
d.eat();
}
}
34

Difference between method overloading and method overriding


Method Overloading Method Overriding
1. Creating more than one method or 1. Creating a method in the derived class with
function having same name but different the same signature as a method in the
signatures or the parameters in the same base class is called as method overriding
class is called method overloading.
2. It is called the compile time polymorphism 2. It is called runtime polymorphism
3. It has the same method name but with 3. It must have same method name as well as
different signatures or the parameters. the signatures or the parameters.
4. Method overloading doesn’t need 4. Method overriding needs inheritance.
inheritance.
5. Method overloading is possible in single
5. Method overriding needs hierarchy level of
class only. the classes i.e. one parent class and other
child class.
6. Access modifier can be any. 6. Access modifier must be public.
7. Method overloading is also called early 7. Method overriding is also called late
binding. binding.

3.3. Abstract Classes and Abstract Methods


Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only essential information to the
user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more
about in the next chapter).
The abstract keyword is used for classes and methods:
 Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).

 Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the derived class (inherited from).
An abstract class can have both abstract and regular methods:
Example
using System;

namespace MyApplication
{
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
35

// Derived class (inherit from Animal)


class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
}

Output

3.4. Inheritance, Interfaces, Encapsulation, Polymorphism, Abstraction and Visual


Inheritance
1. Inheritance
 Inheritance is a mechanism in C# where one class (derived class) inherits the properties and
methods of another class (base class). This promotes code reusability and establishes a natural
hierarchy between classes.
 In C#, inheritance is a process in which one object acquires all the properties and behaviors of
its parent object automatically. In such way, you can reuse, extend or modify the attributes and
behaviors which is defined in other class.
 In C#, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.
Advantage of C# Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is no need to
define the member again. So, less code is required in the class.

C# Single Level Inheritance Example


When one class inherits another class, it is known as single level inheritance. Let's see the example
of single level inheritance given below.
using System;
36

public class Animal Output


{
public void eat() Eating...
{
Console.WriteLine("Eating..."); Barking...
}
}
public class Dog: Animal
{
public void bark()
{
Console.WriteLine("Barking...");
}
}
class TestInheritance2
{
public static void Main(string[] args)
{
Dog d1 = new Dog();
d1.eat();
d1.bark();
}
}

C# Multi Level Inheritance Example


When one class inherits another class which is further inherited by another class, it is known as
multi-level inheritance in C#. Inheritance is transitive so the last derived class acquires all the
members of all its base classes.
Let's see the example of multi-level inheritance in C#.
Output
using System;
public class Animal Eating...
{
public void eat() Barking...
{
Weeping...
Console.WriteLine("Eating...");
}
}
public class Dog: Animal
{
public void bark()
{ Console.WriteLine("Barking...");
}
}
public class BabyDog : Dog
{
public void weep()
{
Console.WriteLine("Weeping...");
}
}
37
class TestInheritance2
{
public static void Main(string[] args)
{
BabyDog d1 = new
BabyDog(); d1.eat();
d1.bark();
d1.weep();
}
}

2. Interfaces
 Interface in C# is a blueprint of a class. It is like abstract class because all the methods which
are declared inside the interface are abstract methods. It cannot have method body and cannot
be instantiated.
 It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve
fully abstraction because it cannot have method body.
 Its implementation must be provided by class or struct. The class or struct which implements
the interface, must provide the implementation of all the methods declared inside the interface.
C# interface example
Let's see the example of interface in C# which has draw() method. Its implementation is provided
by two classes: Rectangle and Circle.
using System; Output
public interface Drawable drawing rectangle...
{
void draw(); drawing circle...
}
public class Rectangle : Drawable
{
public void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Drawable
{
public void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestInterface
{
public static void Main()
{
Drawable d;
d = new Rectangle(); d.draw();
d = new Circle(); d.draw();} }
38

3. Encapsulation
 Encapsulation is the concept of wrapping data into a single unit. It collects data members and
member functions into a single unit called class. The purpose of encapsulation is to prevent
alteration of data from outside. This data can only be accessed by getter functions of the class.
 A fully encapsulated class has getter and setter functions that are used to read and write data.
This class does not allow data access directly.
 Here, we are creating an example in which we have a class that encapsulates properties and
provides getter and setter functions.

Example Output

namespace AccessSpecifiers ID = 101


{
Name = Mohan Ram
class Student
{ Email = [email protected]
// Creating setter and getter for each property
public string ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}

using System;
namespace AccessSpecifiers
{
class Program
{
static void Main(string[] args)
{
Student student = new Student();
// Setting values to the
properties student.ID = "101";
student.Name = "Mohan Ram";
student.Email = "[email protected]";
// getting values
Console.WriteLine("ID = "+student.ID);
Console.WriteLine("Name = "+student.Name)
;
Console.WriteLine("Email = "+student.Email)
;
}
}
}
39

4. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass.
It is the ability of different classes to respond to the same method call in different ways.
Example of Polymorphism:
 The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms.
It is a greek word. In object-oriented programming, we use 3 main concepts: inheritance,
encapsulation and polymorphism.
 There are two types of polymorphism in C#: compile time polymorphism and runtime
polymorphism.
 Compile time polymorphism is achieved by method overloading and operator overloading in
C#. It is also known as static binding or early binding.
 Runtime polymorphism in achieved by method overriding which is also known as dynamic
binding or late binding.

C# Runtime Polymorphism Example


Let's see a simple example of runtime polymorphism in C#.

using System; Output


public class Animal{
public virtual void eat(){ eating bread...
Console.WriteLine("eating...");
}
}
public class Dog: Animal
{
public override void eat()
{
Console.WriteLine("eating bread...");
}

}
public class TestPolymorphism
{
public static void Main()
{
Animal a= new Dog();
a.eat();
}
}

C# Runtime Polymorphism Example 2


Let's see a another example of runtime polymorphism in C# where we are having two derived
classes.
using System;
public class Shape{
public virtual void draw(){
Console.WriteLine("drawing...");
}}
40

public class Rectangle: Shape Output


{
public override void draw() drawing...
{ drawing rectangle...
Console.WriteLine("drawing rectangle..."); drawing circle...
}

}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}

}
public class TestPolymorphism
{
public static void Main()
{
Shape s;
s = new
Shape();
s.draw();
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();

}
}
5. Abstraction
 Abstraction is the concept of hiding the complex implementation details and showing only the
essential features of the object. It allows you to focus on what the object does rather than how
it does it.
 Data abstraction is the process of hiding certain details and showing only essential
information to the user.
 Abstraction can be achieved with either abstract classes or interfaces.
 The abstract keyword is used for classes and methods:
 Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
 Abstract method: can only be used in an abstract class, and it does not have a body. The body
is provided by the derived class (inherited from).

Example of Abstraction
using System;
public abstract class Shape
{
public abstract void draw();
}
41

public class Rectangle : Shape Output


{
public override void draw() drawing rectangle...
{ drawing circle...
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestAbstract
{
public static void Main()
{
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
}
}

6. Visual Inheritance
Visual Inheritance in C# is a feature in Visual Studio that allows developers to create derived
forms (or controls) that inherit the visual interface of a base form (or control). This is particularly
useful in Windows Forms applications, where you can create a base form with common UI
elements and then derive other forms from it.

Example of Visual Inheritance:


Visual Inheritance is primarily a design-time feature in Visual Studio, and it involves working with
forms. Below is a conceptual outline of how it works, as it's not easily demonstrated with a simple
code example.
i) Create a Base Form:
o Design a base form (BaseForm) with common UI elements like buttons, labels, etc.

// This would be in
BaseForm.cs public class
BaseForm : Form
{
protected Button commonButton;

public BaseForm()
{
InitializeComponent();
}
42

private void InitializeComponent()


{
this.commonButton = new
System.Windows.Forms.Button(); this.SuspendLayout();
//
// commonButton
//
this.commonButton.Location = new System.Drawing.Point(50, 50);
this.commonButton.Name = "commonButton";
this.commonButton.Size = new System.Drawing.Size(100, 23);
this.commonButton.TabIndex = 0;
this.commonButton.Text = "Common Button";
this.commonButton.UseVisualStyleBackColor =
true; this.ResumeLayout(false);
}
}

ii) Create a Derived Form:


 In Visual Studio, create a new form that inherits from BaseForm.

// This would be in DerivedForm.cs


public class DerivedForm : BaseForm
{
public DerivedForm()
{
InitializeComponent();
}

private void InitializeComponent()


{
this.Text = "Derived Form";
}
}

iii) Run the Application:


 When you run the application, the DerivedForm will inherit all the visual elements from
BaseForm and can add more elements or override existing ones.

3.5. Exceptional handling: System defined exceptions and custom exceptions,


Throwing Exceptions
 Exception Handling in C# is a process to handle runtime errors. We perform exception handling
so that normal flow of the application can be maintained even after runtime errors.
 In C#, exception is an event or object which is thrown at runtime. All exceptions the derived
from System.Exception class. It is a runtime error which can be handled. If we don't handle
the exception, it prints exception message and terminates the program.
Advantage
43

It maintains the normal flow of the application. In such case, rest of the code is executed event after
exception.
C# Exception Handling Keywords
In C#, we use 4 keywords to perform exception handling:
o try
o catch
o finally, and
o throw

C# try/catch example
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }

Console.WriteLine("Rest of the code");


}
}

Output:

C# finally
C# finally block is used to execute important code which is to be executed whether exception is
handled or not. It must be preceded by catch or try block.
C# finally example if exception is handled
using System;
public class Example
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
44

{
Console.WriteLine("Finally block is executed");
}
Console.WriteLine("Rest of the code");
}
}

Output:

1. System-Defined Exceptions
System-defined exceptions are exceptions that are part of the .NET framework and are raised when
common errors occur during program execution.
Example of System-Defined Exceptions:
Example 1
using System;

class Program
{
static void Main(string[] args)
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"Caught an exception: {ex.Message}");
}
finally
{
Console.WriteLine("This block is always executed.");
}
}
}

Output:
45

Example 2
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a /
b;
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{ Console.WriteLine("Finally block is executed");
}
Console.WriteLine("Rest of the code");
}
}
Output:

Explanation:
 The try block contains code that may cause an exception.
 The catch block catches and handles the Exception e.
 The finally block always executes, whether an exception was caught or not.

2. Custom/User-defined Exceptions
 In addition to using system-defined exceptions, you can create custom exceptions to
represent specific error conditions in your application. Custom exceptions are typically
derived from the System.Exception class.
 C# allows us to create user-defined or custom exception. It is used to make the meaningful
exception. To do this, we need to inherit Exception class.
Example of a Custom Exception:
To create a user-defined exception, you need to create a new class that inherits from the
System.Exception class or one of its derived classes.

using System;

public class CustomException : Exception


{
public CustomException(string message) : base(message)
{
46

}
}

class Program
{
static void Main(string[] args)
{
try
{
throw new CustomException("This is a custom exception.");
}
catch (CustomException ex)
{
Console.WriteLine($"Custom Exception: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Exception: {ex.Message}");
}
}
}

Output:

Custom Exception Example 2


using System;
public class InvalidAgeException : Exception
{
public InvalidAgeException(String message)
: base(message)
{

}
}
public class TestUserDefinedException
{
static void validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be great an 18");
}
}
public static void Main(string[] args)
{
try
{
validate(12);}
47
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}

Output:

3. Throwing Exceptions
The throw keyword is used to explicitly raise an exception. You can throw system-defined
exceptions or custom exceptions.
Example of Throwing Exceptions:
using System;

class Program
{
static void Main(string[] args)
{
try
{
int dividend = 10;
int divisor = 0;
if (divisor ==
0)
{
throw new DivideByZeroException("Cannot divide by zero.");
}
int result = dividend / divisor;
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Caught an exception: {ex.Message}");
}
}
}

Output:

Explanation:
 The throw statement is used to raise a DivideByZeroException when an attempt to divide by
zero is detected.
 The catch block catches the exception and prints the error message.
48

Example 2
using System;

namespace MyApplication
{
class Program
{
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}
}

static void Main(string[] args)


{
checkAge(20);
}
}
}

Output

3.6. Parallel Programs, Concurrent Collections


Parallel programming and concurrent collections are key concepts in C# that allow you to write
efficient, thread-safe code that can perform multiple tasks simultaneously.

1. Parallel Programming
Parallel programming in C# can be achieved using the System.Threading.Tasks namespace, which
provides several ways to run code concurrently, including Parallel.For, Parallel.ForEach, and the
Task class.

Example of Parallel Programming:


using System;
using System.Threading.Tasks;

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Parallel For
loop:"); Parallel.For(0, 10, i =>
{
49

Console.WriteLine($"Processing number {i} on thread {Task.CurrentId}");


});

Console.WriteLine("\nParallel ForEach
loop:"); int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8,
9, 10 };
Parallel.ForEach(numbers, number =>
{
Console.WriteLine($"Processing number {number} on thread {Task.CurrentId}");
});

Console.WriteLine("\nParallel Tasks:");
Task task1 = Task.Run(() => PrintNumbers("Task
1")); Task task2 = Task.Run(() =>
PrintNumbers("Task 2")); Task.WaitAll(task1, task2);
}

static void PrintNumbers(string taskName)


{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"{taskName} - Number: {i}");
}
}
}
Output:
Parallel For loop:
Processing number 0 on thread 1
Processing number 1 on thread 3
Processing number 2 on thread 2
Processing number 3 on thread 4
Processing number 4 on thread 1
Processing number 5 on thread 3
Processing number 6 on thread 2
Processing number 7 on thread 4
Processing number 8 on thread 1
Processing number 9 on thread 3

Parallel ForEach loop:


Processing number 1 on thread 2
Processing number 2 on thread 1
Processing number 3 on thread 3
Processing number 4 on thread 4
Processing number 5 on thread 2
Processing number 6 on thread 1
Processing number 7 on thread 3
Processing number 8 on thread 4
Processing number 9 on thread 2
Processing number 10 on thread 1
50

Parallel Tasks:
Task 1 - Number: 1
Task 1 - Number: 2
Task 1 - Number: 3
Task 1 - Number: 4
Task 1 - Number: 5
Task 2 - Number: 1
Task 2 - Number: 2
Task 2 - Number: 3
Task 2 - Number: 4
Task 2 - Number: 5

Explanation:
 Parallel.For: This method runs a for loop in parallel, distributing the iterations across multiple
threads.
 Parallel.ForEach: This method works like Parallel.For, but is used for iterating over collections.
 Tasks: Tasks represent asynchronous operations. The Task.Run method is used to run a
method asynchronously, and Task.WaitAll waits for all tasks to complete.

2. Concurrent Collections
Concurrent collections in C# are part of the System.Collections.Concurrent namespace and are
designed to handle multi-threaded scenarios safely. Common concurrent collections include
ConcurrentDictionary, ConcurrentQueue, ConcurrentStack, and ConcurrentBag.

Example of Concurrent Collections:


using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

class Program
{
static void Main(string[] args)
{
ConcurrentDictionary<int, string> dict = new ConcurrentDictionary<int, string>();

Parallel.For(0, 10, i =>


{
dict.TryAdd(i, $"Value {i}");
});

Console.WriteLine("ConcurrentDictionary contents:");
foreach (var kvp in dict)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
ConcurrentQueue<int> queue = new ConcurrentQueue<int>();

Parallel.For(0, 10, i =>


{
queue.Enqueue(i);
});
51
Console.WriteLine("\nConcurrentQueue
contents:"); while (queue.TryDequeue(out int
result))
{
Console.WriteLine(result);
}
}
}

Output:
ConcurrentDictionary contents:
0: Value 0
1: Value 1
2: Value 2
3: Value 3
4: Value 4
5: Value 5
6: Value 6
7: Value 7
8: Value 8
9: Value 9

ConcurrentQueue
contents: 0
1
2
3
4
5
6
7
8
9
Explanation:
 ConcurrentDictionary: A thread-safe dictionary where you can add, update, or remove key-
value pairs concurrently.
 ConcurrentQueue: A thread-safe FIFO (First-In-First-Out) collection that allows multiple
threads to enqueue and dequeue items safely.
52

Unit 4
ADO.NET and WPF (Windows Presentation Foundation)

4.1. Data access Technologies


Data Access Technologies refer to the tools and methods used to interact with databases or data
sources. Over the years, different technologies have been developed to simplify data access:
 ADO.NET (Active Data Objects.NET): A set of libraries in the .NET framework that provides a
bridge between applications and databases.
 Entity Framework: An Object-Relational Mapper (ORM) that enables .NET developers to work
with databases using .NET objects.
 LINQ to SQL: Allows querying and manipulating data using LINQ (Language Integrated Query)
syntax.
 ODBC, OLE DB: Older technologies used to interact with various data sources in a standardized
way.
 Dapper: A lightweight micro-ORM library for mapping database objects to C# objects.

4.2. ADO.NET Architecture


ADO stands for Active Data Objects. ADO.NET is one of Microsoft’s Data Access Technologies
using which we can communicate with different data sources. It is a part of the .NET Framework
which is used to establish a connection between the .NET Application and different data sources.
So, ADO.NET is nothing but a component in .NET Framework that helps us to fetch data from
different data sources to our C#.NET or VB.NET Applications as well as also used to send data from
our C#.NET or VB.NET Application to different data sources such as SQL Server, Oracle, MySQL,
XML, etc.

The Architecture of ADO.NET:


The ADO.NET Architecture is comprised of 6 important components. They are as follows:
1. Connection
2. Command
3. DataReader
4. DataAdapter
5. DataSet
6. DataView

From the above components, two components are compulsory. One is the command object and the
other one is the connection object. Irrespective of the operations like Insert, Update, Delete and Select,
the command and connection object you always need. For a better understanding, please have a look at
the following image.
53

OR

Fig: Architecture of ADO.NET


Let us understand each of the components in detail.
1. Connection:
The first important component of ADO.NET Architecture is the Connection Object. The
Connection Object is required to connect with your backend database which can be SQL Server,
54

Oracle, MySQL, etc. To create a connection object, you need at least two things. The first one is
where is your database located i.e. the Machine name or IP Address or someplace where your
database is located. And the second thing is the security credentials i.e. whether it is a Windows
authentication or SQL Authentication i.e. user name and password-based authentication. So, the
first is to create the connection object and the connection object is required to connect the front-
end application with the backend data source.
2. Command:
The Second important component of ADO.NET Architecture is the Command Object. When we
talk about databases like SQL Server, Oracle, MySQL, etc., we know one thing, these databases
only understand SQL. The Command Object is the component where you go and write your SQL
queries. Later you take the command object and execute it over the connection. That means using
the command object, you can fetch data or send data to the database i.e. performing the Database
CRUD Operations.
Note: From the Command Object onwards, you can go in two different ways. One is you can go
with the DataSet way and the other is, you can go with the DataReader way. Which way you
need to choose, basically will depend on the situation.
3. DataReader:
DataReader is a read-only connection-oriented recordset that helps us to read the records only in
the forward mode. Here, you need to understand three things i.e. read-only, connection-oriented,
and forward mode. Read-Only means using DataReader, we cannot Insert, Update, and Delete the
data. Connection-Oriented means, it always requires an active and open connection to fetch the
data. Forward mode means you can always read the next record, there is no way that you can read
the previous record.
4. DataSet:
It is a Disconnected record set that can be browsed in both i.e. forward and backward mode. It is
not read-only i.e. you can update the data present in the data set. Actually, DataSet is a
collection of DataTables that holds the data and we can add, update, and delete data in a data
table. DataSet gets filled by somebody called DataAdapter.
5. DataAdapter:
The DataAdapter is one of the Components of ADO.NET which acts as a bridge between the
command object and the dataset. What the DataAdapter does is, it takes the data from the
command object and fills the data set.
6. DataView Class
The DataView class enables us to create different views of the data stored in a DataTable. This is
most often used in data-binding applications. Using a DataView, we can expose the data in a table
with different sort orders, and you can filter the data by row state or based on a filter expression.
CommandBuilder:
Automatically generates SQL commands based on changes made to the DataSet, simplifying the
process of updating the database.

4.3. Data access using ADO.NET


ADO.NET provides a set of classes that enable you to interact with various data sources, primarily
relational databases like SQL Server, Oracle, etc. Below, we'll explore how to perform common data
access tasks using ADO.NET, including connecting to a database, executing queries, retrieving data,
and updating data.
1. Connecting to a Database
To connect to a database, you'll use a Connection object. This object requires a connection string
that contains information such as the database server, database name, and authentication details.
55

Example: Connecting to SQL Server


using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();
Console.WriteLine("Connection to the database is successful.");
}
}
}

Output
Connection to the database is successful.

2. Executing a SQL Command


The Command object is used to execute SQL queries and commands against the database. It can be
used to perform operations such as SELECT, INSERT, UPDATE, and DELETE.
Example: Executing a SELECT Query
using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string query = "SELECT EmployeeID, FirstName, LastName FROM Employees";


SqlCommand command = new SqlCommand(query, connection);

SqlDataReader reader =
command.ExecuteReader(); while (reader.Read())
{
Console.WriteLine($"{reader["EmployeeID"]}, {reader["FirstName"]},
56

{
reader["LastName"]}");
}
reader.Close();
}
}
}

Output
1, John, Doe

2, Jane, Smith

3. Inserting Data into the Database


You can insert data into the database using the INSERT SQL command.
Example: Inserting a New Record
using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string insertQuery = "INSERT INTO Employees (FirstName, LastName) VALUES


(@FirstName, @LastName)";
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@FirstName", "Michael");
command.Parameters.AddWithValue("@LastName", "Jordan");

int rowsAffected = command.ExecuteNonQuery();


Console.WriteLine($"{rowsAffected} row(s) inserted.");
}
}
}

Output
1 row(s) inserted.
57

4. Updating Data in the Database


You can update existing data in the database using the UPDATE SQL command.
Example: Updating a Record
using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

string updateQuery = "UPDATE Employees SET LastName = @LastName WHERE


EmployeeID = @EmployeeID";
SqlCommand command = new SqlCommand(updateQuery, connection);
command.Parameters.AddWithValue("@LastName", "Bryant");
command.Parameters.AddWithValue("@EmployeeID", 1);

int rowsAffected = command.ExecuteNonQuery();


Console.WriteLine($"{rowsAffected} row(s) updated.");
}
}
}

Output

1 row(s) updated.

5. Deleting Data from the Database


You can delete data from the database using the DELETE SQL command.
Example: Deleting a Record
using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User
Id=your_username;Password=your_password;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();
58

string deleteQuery = "DELETE FROM Employees WHERE EmployeeID = @EmployeeID";


SqlCommand command = new SqlCommand(deleteQuery, connection);
command.Parameters.AddWithValue("@EmployeeID", 2);

int rowsAffected = command.ExecuteNonQuery();


Console.WriteLine($"{rowsAffected} row(s) deleted.");
}
}
}

Output
1 row(s) deleted.

4.4. ADO.NET Connections: .NET Data providers, Connection classes, Strings,


Pooling, Events
ADO.NET is designed to work with various types of databases. This section will explore the different
aspects of connections in ADO.NET, including .NET Data Providers, Connection classes, Connection
strings, Connection pooling, and Events.

.NET Data Providers


.NET Data Providers are the fundamental components in ADO.NET, providing the necessary classes
for connecting, executing commands, and retrieving data from a database. Common providers include:
 SqlClient: For SQL Server.
 OracleClient: For Oracle databases.
 OleDb: For accessing databases using OLE DB.
 Odbc: For accessing databases using ODBC.

Connection Classes
Each data provider includes a connection class that establishes a connection to the database. The most
common connection classes are:
 SqlConnection: For SQL Server.
 OracleConnection: For Oracle databases.
 OleDbConnection: For databases using OLE DB.
 OdbcConnection: For databases using ODBC.

Connection Strings
Connection strings contain the information required to establish a connection to a database, such as the
server name, database name, and credentials.
Example: SQL Server Connection String
"Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"

Connection Pooling
Connection pooling improves performance by reusing existing connections instead of opening and
closing connections for each request. This reduces the overhead associated with establishing new
connections.
59

Example: Enabling Connection Pooling


"Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;Pooling=true;Min Pool Size=5;Max Pool Size=100;"
Events
ADO.NET connection classes provide events such as StateChange, InfoMessage, and Disposed, which
can be used to handle specific actions when certain events occur.
Example: Handling the StateChange Event
using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User
Id=myUsername;Password=myPassword;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.StateChange += new StateChangeEventHandler(OnStateChange);
connection.Open();
Console.WriteLine("Connection opened.");
}
}

private static void OnStateChange(object sender, StateChangeEventArgs e)


{
Console.WriteLine($"Connection state changed from {e.OriginalState} to {e.CurrentState}.");
}
}

Output
Connection state changed from Closed to Open.
Connection opened.
Connection state changed from Open to Closed.

Full Code Example: Connecting to SQL Server with Connection Pooling and Events
using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
60

string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;


Password=myPassword;Pooling=true;Min Pool Size=5;Max Pool Size=100;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.StateChange += new StateChangeEventHandler(OnStateChange);

connection.Open();
Console.WriteLine("Connection
opened.");

// Perform database operations here

connection.Close();
Console.WriteLine("Connection closed.");
}
}

private static void OnStateChange(object sender, StateChangeEventArgs e)


{
Console.WriteLine($"Connection state changed from {e.OriginalState} to
{e.CurrentState}.");
}
}

Output:
Connection state changed from Closed to Open.
Connection opened.
Connection state changed from Open to Closed.
Connection closed.

4.5. ADO.NET commands: Command object, creating, executing commands,


ADO.NET commands are central to interacting with a database. The Command object allows you to
execute SQL statements or stored procedures against a data source. This section will explain the role
of the Command object, how to create commands, and how to execute them with code examples and a
supporting table/diagram.
Component Description
Command Object Represents a SQL statement or stored procedure to execute against a data
source.
CommandText The SQL statement or stored procedure to be executed.

CommandType Specifies how the CommandText is interpreted (e.g., Text,


StoredProcedure).
Parameters A collection of parameters associated with the command, used to pass
values.
61

ExecuteReader() Executes a command that returns rows. Returns a DataReader.

ExecuteNonQuery() Executes a command that does not return rows (e.g., INSERT, UPDATE,
DELETE).
ExecuteScalar() Executes a command and returns a single value (e.g., aggregate functions).

ExecuteXmlReader() Executes a command that returns XML.

1. Command Object
The Command object in ADO.NET represents a SQL command or stored procedure to be
executed. It is part of the .NET Data Provider's namespace and is specific to each type of database:
 SqlCommand: Used with SQL Server.
 OleDbCommand: Used with OLE DB data sources.
 OdbcCommand: Used with ODBC data sources.

2. Creating a Command
To create a command, you instantiate a Command object, set its properties (like CommandText
and CommandType), and then execute it using one of the available methods (ExecuteReader,
ExecuteNonQuery, ExecuteScalar, ExecuteXmlReader).
Example: Creating a SqlCommand Object
using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

// Create a command object


SqlCommand command = new
SqlCommand(); command.Connection =
connection;
command.CommandText = "SELECT COUNT(*) FROM Employees";
command.CommandType = System.Data.CommandType.Text;

int employeeCount = (int)command.ExecuteScalar();


Console.WriteLine("Total Employees: " + employeeCount);
}
}
}
62

Output:
Total Employees: 100

3. Executing Commands
There are different methods to execute a command depending on what you want to achieve:
a. ExecuteReader()
Used when you need to retrieve rows from a data source.
using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

SqlCommand command = new SqlCommand("SELECT EmployeeID, FirstName,


LastName FROM Employees", connection);

using (SqlDataReader reader = command.ExecuteReader())


{
while (reader.Read())
{
Console.WriteLine($"{reader["EmployeeID"]}, {reader["FirstName"]},
{reader["LastName"]}");
}
}
}
}
Output:
1, John, Doe
2, Jane, Smith

4. Working with Parameters


When executing a command, especially with user inputs, it's crucial to use parameters to prevent
SQL injection and ensure type safety.
63

Example: Using Parameters with SqlCommand

using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User
Id=myUsername;Password=myPassword;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

SqlCommand command = new SqlCommand("INSERT INTO Employees (FirstName,


LastName) VALUES (@FirstName, @LastName)", connection);
command.Parameters.AddWithValue("@FirstName", "Michael");
command.Parameters.AddWithValue("@LastName", "Jordan");

int rowsAffected = command.ExecuteNonQuery();


Console.WriteLine($"{rowsAffected} row(s) inserted.");
}
}
}

Output:
1 row(s) inserted....

4.6. Batch queries and stored procedures


Batch queries and stored procedures are powerful tools for database interaction in ADO.NET. They
allow you to perform multiple database operations in a single round trip to the server, improving
efficiency and reducing network overhead.

1. Batch Queries
Batch queries involve executing multiple SQL statements in a single database round trip. This is
particularly useful when you want to perform multiple operations (like inserts, updates, and deletes)
together.
Example: Executing a Batch Query with ExecuteNonQuery()
using System;
using System.Data.SqlClient;

class Program
{
64

static void Main()


{
string connectionString =
"Server=myServerAddress;Database=myDataBase; User
Id=myUsername;Password=myPassword;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

// Batch query with multiple SQL


statements string batchQuery = @"
INSERT INTO Employees (FirstName, LastName) VALUES ('John', 'Doe');
INSERT INTO Employees (FirstName, LastName) VALUES ('Jane', 'Smith');
UPDATE Employees SET LastName = 'Johnson' WHERE FirstName = 'John';
DELETE FROM Employees WHERE FirstName = 'Jane' AND LastName = 'Smith';";

SqlCommand command = new SqlCommand(batchQuery,


connection); int rowsAffected = command.ExecuteNonQuery();

Console.WriteLine($"{rowsAffected} row(s) affected.");


}
}
}

Output:
2 row(s) affected. // Total number of affected rows across all operations

2. Stored Procedures
Stored procedures are precompiled collections of SQL statements stored in the database. They can
accept parameters, perform complex operations, and return results. They are efficient because they are
compiled and stored in the database, reducing the need to send SQL code over the network repeatedly.
Example: Creating and Executing a Stored Procedure
1. Create a Stored Procedure in SQL Server
CREATE PROCEDURE GetEmployeeCountByDepartment
@DepartmentName NVARCHAR(50)
AS
BEGIN
SELECT COUNT(*) AS
EmployeeCount FROM Employees
WHERE Department =
@DepartmentName; END;

2. Execute the Stored Procedure in C#


using System;
using System.Data.SqlClient;

class Program
{
65
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

// Create command to execute stored procedure


SqlCommand command = new SqlCommand("GetEmployeeCountByDepartment",
connection);
command.CommandType = System.Data.CommandType.StoredProcedure;

// Add parameter to the stored procedure


command.Parameters.AddWithValue("@DepartmentName", "Sales");

// Execute the stored procedure and get the result


int employeeCount = (int)command.ExecuteScalar();
Console.WriteLine("Total Employees in Sales: " + employeeCount);
}
}
}

Output:

Total Employees in Sales: 5

3. Executing Stored Procedures with Multiple Result Sets


Stored procedures can return multiple result sets, and you can retrieve these using
ExecuteReader().
Example: Executing a Stored Procedure with Multiple Result Sets
1. Create a Stored Procedure that Returns Multiple Result Sets
CREATE PROCEDURE GetEmployeeAndDepartmentDetails
AS
BEGIN
SELECT * FROM Employees;
SELECT * FROM
Departments;
END;
2. Execute the Stored Procedure in C#
using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
66

string connectionString = "Server=myServerAddress;Database=myDataBase;


User Id=myUsername;Password=myPassword;";

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();

// Create command to execute stored


procedure SqlCommand command = new
SqlCommand("GetEmployeeAndDepartmentDetails", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;

using (SqlDataReader reader = command.ExecuteReader())


{
// Read the first result set (Employees)
Console.WriteLine("Employees:");
while (reader.Read())
{
Console.WriteLine($"{reader["EmployeeID"]}, {reader["FirstName"]},
{reader["LastName"]}");
}

// Move to the next result set (Departments)


if (reader.NextResult())
{
Console.WriteLine("\nDepartments:");
while (reader.Read())
{
Console.WriteLine($"{reader["DepartmentID"]},
{reader["DepartmentName"]}");
}
}
}
}
}
}
Output:
Employees:
1, John, Doe
2, Jane, Smith

Departments:
1, Sales
2, Marketing
67

4.7. Datasets, DataTable, DataRow, DataColumn and updating database from a


DataSet In ADO.NET, DataSet, DataTable, DataRow, and DataColumn are key classes for working
with in- memory data. A DataSet can represent a complete set of data, including related tables, while
DataTable represents a single table of in-memory data. DataRow and DataColumn allow you to work
with individual rows and columns of a DataTable.
1. DataSet
A DataSet is an in-memory representation of data, which can contain multiple DataTable objects.
It is a collection of tables, relationships, and constraints. You can think of it as a mini-database
stored in memory.
2. DataTable
A DataTable represents a single table of in-memory data. It consists of rows (DataRow objects)
and columns (DataColumn objects).
3. DataRow
A DataRow represents a single row of data in a DataTable. It provides methods to access, modify,
and delete the data within a row.
4. DataColumn
A DataColumn represents a column of data within a DataTable. It defines the type of data that can
be stored in the column.
5. DataAdapter
A DataAdapter acts as a bridge between a DataSet and a data source. It is responsible for filling the
DataSet with data from the database and for updating the database based on changes made in the
DataSet.
Example: Working with DataSet, DataTable, DataRow, and DataColumn
1. Creating and Filling a DataSet
Let's start by creating a DataSet and filling it with data from a database.
using System;
using
System.Data;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";
string selectCommandText = "SELECT EmployeeID, FirstName, LastName FROM Employees";

SqlDataAdapter dataAdapter = new SqlDataAdapter(selectCommandText, connectionString);


DataSet dataSet = new DataSet();

// Fill the DataSet with data from the database


dataAdapter.Fill(dataSet, "Employees");

// Access the DataTable within the DataSet


DataTable employeesTable = dataSet.Tables["Employees"];

// Iterate through the rows in the DataTable


foreach (DataRow row in employeesTable.Rows)
68
{
Console.WriteLine($"EmployeeID: {row["EmployeeID"]}, Name: {row["FirstName"]}
{row["LastName"]}");
}
}
}

Output:
EmployeeID: 1, Name: John Doe
EmployeeID: 2, Name: Jane
Smith
2. Modifying Data and Updating the Database
Next, let's modify the data in the DataSet and update the database.
using System;
using
System.Data;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";
string selectCommandText = "SELECT EmployeeID, FirstName, LastName FROM Employees";

SqlDataAdapter dataAdapter = new SqlDataAdapter(selectCommandText, connectionString);


SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet dataSet = new DataSet();

// Fill the DataSet with data from the database


dataAdapter.Fill(dataSet, "Employees");

// Access the DataTable within the DataSet


DataTable employeesTable = dataSet.Tables["Employees"];

// Modify data in the DataTable


DataRow rowToUpdate = employeesTable.Rows[0];
rowToUpdate["LastName"] = "Smith";

// Add a new row to the DataTable


DataRow newRow =
employeesTable.NewRow();
newRow["FirstName"] = "Michael";
newRow["LastName"] = "Jordan";
69
// Delete a row from the DataTable
employeesTable.Rows[1].Delete();

// Update the database with the changes made to the DataSet


dataAdapter.Update(dataSet, "Employees");

// Display the updated data


Console.WriteLine("Updated Data:");
foreach (DataRow row in employeesTable.Rows)
{
Console.WriteLine($"EmployeeID: {row["EmployeeID"]}, Name: {row["FirstName"]}
{row["LastName"]}");
}
}
}

Output:

Updated Data:
EmployeeID: 1, Name: John Smith
EmployeeID: 3, Name: Michael Jordan

Explanation:
1. Filling the DataSet:
o The SqlDataAdapter is used to fill the DataSet with data from the Employees table in the
database.
o The DataSet contains a DataTable named "Employees".
2. Modifying Data:
o We modify the last name of the first employee.
o A new employee ("Michael Jordan") is added to the DataTable.
o The second employee ("Jane Smith") is deleted from the DataTable.
3. Updating the Database:
o The SqlDataAdapter is used to update the database with the changes made in the DataSet.
o The SqlCommandBuilder automatically generates the necessary SQL commands (INSERT,
UPDATE, DELETE) based on the modifications in the DataTable.

4.8 LINQ to SQL and DataSet


LINQ (Language Integrated Query) to SQL is a powerful ORM (Object-Relational Mapping) tool in
.NET that allows you to interact with the database using strongly-typed objects. LINQ to SQL
provides a rich, object-oriented way to query and update the database. When combined with DataSet,
you can leverage both disconnected data and LINQ’s querying capabilities for more efficient data
manipulation.

LINQ to SQL with DataContext


The DataContext class in LINQ to SQL is responsible for managing the connection to the
database, submitting changes, and translating LINQ queries into SQL commands. You can think of
DataContext as the bridge between the database and your LINQ queries.
70

1. Setting Up LINQ to SQL


Before diving into examples, ensure you have a database with a table that you can use for
querying. For this example, let's assume we have a Products table in a SQL Server database.
Create a SQL Server Database with a Products Table

CREATE TABLE Products (


ProductID INT PRIMARY KEY IDENTITY,
ProductName NVARCHAR(100),
Price DECIMAL(18, 2)
);

INSERT INTO Products (ProductName, Price) VALUES ('Laptop', 800.00);


INSERT INTO Products (ProductName, Price) VALUES ('Smartphone', 500.00);
INSERT INTO Products (ProductName, Price) VALUES ('Tablet', 300.00);

2. Working with LINQ to SQL in C#


Next, we will use LINQ to SQL to query the Products table and load the data into a DataSet.
Example: LINQ to SQL Query and Loading Data into a DataSet
using System;
using
System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;

class Program
{
static void Main()
{
// Define the connection string
string connectionString = "Server=myServerAddress;Database=myDataBase;
User Id=myUsername;Password=myPassword;";

// Create a DataContext
DataContext dataContext = new DataContext(connectionString);

// Define a table for the Products entity


Table<Product> products = dataContext.GetTable<Product>();

// Query the Products table using LINQ


var query = from product in
products where product.Price
> 300 select product;
// Create a DataSet and a DataTable to hold the data
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable("Products");
71

// Define the columns for the DataTable


dataTable.Columns.Add("ProductID", typeof(int));
dataTable.Columns.Add("ProductName", typeof(string));
dataTable.Columns.Add("Price", typeof(decimal));

// Populate the DataTable with the results of the LINQ query


foreach (var product in query)
{
DataRow row = dataTable.NewRow();
row["ProductID"] = product.ProductID;
row["ProductName"] = product.ProductName;
row["Price"] = product.Price;
dataTable.Rows.Add(row);
}

// Add the DataTable to the DataSet


dataSet.Tables.Add(dataTable);

// Display the data


Console.WriteLine("Products with Price > 300:");
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine($"ProductID: {row["ProductID"]}, Name: {row["ProductName"]},
Price: {row["Price"]}");
}
}
}

// Define the Product entity class


[Table(Name = "Products")]
public class Product
{
[Column(IsPrimaryKey = true)]
public int ProductID { get; set; }

[Column]
public string ProductName { get; set; }

[Column]
public decimal Price { get; set; }
}

Output:
Products with Price > 300:
ProductID: 1, Name: Laptop, Price: 800.00
ProductID: 2, Name: Smartphone, Price: 500.00
72

Explanation:
1. DataContext and Product Entity:
o DataContext is used to manage the connection and translate LINQ queries to SQL.
o The Product class is decorated with [Table] and [Column] attributes, mapping it to the
Products table in the database.
2. LINQ Query:
o The LINQ query retrieves products where the price is greater than 300.
o The results are loaded into a DataTable within a DataSet.
3. Loading Data into DataSet:
o The DataTable is defined with columns corresponding to the Products table.
o The query results are added as rows in the DataTable, which is then added to the DataSet.
4. Displaying Data:
o The contents of the DataTable are displayed, showing products with prices greater than 300.

4.9 WPF Controls, Layouts, Dialogs, Menus, Commands and Data bindings
WPF is known as Windows Presentation Foundation. Windows Presentation Foundation is known as
the development framework. WPF is also known as the sub-system of the .Net framework. Windows
Presentation Foundation framework can build the Windows Client Application. Windows Application
can run on the Windows Operating System. We use XAML language for the frontend and C# language
as the backend.
Windows Presentation Foundation (WPF) is a powerful UI framework in .NET that allows developers
to create rich and interactive applications. This section covers WPF controls, layouts, dialogs, menus,
commands, and data bindings.
WPF employs XAML, which is an XML based language. XML is used to define and link the various
elements. An application that is developed with the use of the WPF, we can deploy them as the
Standalone desktop programs, or we can host the WPF applications as the embedded object on a
website.

The complete inheritance hierarchy of WPF controls are as follows −


73

1. WPF Controls
WPF Controls are the building blocks for any user interface in a WPF application. Common controls
include Button, TextBox, Label, ListBox, etc.
Example: Basic WPF Controls
XML
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Controls Example" Height="200" Width="300">
<StackPanel Margin="10">
<TextBlock Text="Enter your name:" />
<TextBox Name="nameTextBox" Width="200" Margin="0,5,0,5"/>
<Button Content="Submit" Click="SubmitButton_Click" Width="200"/>
<Label Name="outputLabel" Margin="0,10,0,0"/>
</StackPanel>
</Window>

Csharp
using System.Windows;

namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void SubmitButton_Click(object sender, RoutedEventArgs e)


{
outputLabel.Content = "Hello, " + nameTextBox.Text + "!";
}
}
}

Output:
A simple UI where the user enters their name in a text box. When the "Submit" button is clicked, a
greeting message is displayed in the label.
Visual Diagram:
 StackPanel arranges the controls vertically.
 TextBlock prompts the user for input.
 TextBox captures user input.
 Button triggers an action when clicked.
 Label displays the result.
74

2. Layouts
Layouts in WPF determine how UI elements are arranged on the screen. Some common layout
panels include Grid, StackPanel, DockPanel, and Canvas.
Example: Using Grid Layout

XML
<<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Layout Example" Height="200" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>

<TextBlock Text="Username:" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center"/>


<TextBox Grid.Row="0" Grid.Column="1" Width="150" Margin="5"/>

<TextBlock Text="Password:" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center"/>


<PasswordBox Grid.Row="1" Grid.Column="1" Width="150" Margin="5"/>

<Button Content="Login" Grid.Row="2" Grid.Column="1" HorizontalAlignment="Right"


Margin="5"/>
</Grid>
</Window>
Output:
A simple login form with labeled text boxes for username and password, arranged in a grid layout.
Visual Diagram:
 Grid Layout organizes controls in rows and columns.
 TextBlock prompts for the username and password.
 TextBox and PasswordBox are input fields.
 Button triggers the login action.

3. Dialogs
Dialogs are windows that prompt the user to provide information or make decisions. WPF
provides several built-in dialogs like MessageBox, OpenFileDialog, and SaveFileDialog.

Example: Using MessageBox


75

Csharp
private void ShowMessageBox()
{
MessageBoxResult result = MessageBox.Show("Do you want to continue?", "Confirmation",
MessageBoxButton.YesNo, MessageBoxImage.Question);

if (result == MessageBoxResult.Yes)
{
MessageBox.Show("You chose to continue.", "Information", MessageBoxButton.OK,
MessageBoxImage.Information);
}
else
{
MessageBox.Show("You chose not to continue.", "Information", MessageBoxButton.OK,
MessageBoxImage.Information);
}
}

Output:
A dialog box asking the user if they want to continue, with subsequent messages based on the
user's choice.
Visual Diagram:
 MessageBox shows a prompt with Yes/No options.
 Result Handling determines the next step based on user input.

4. Menus
Menus are used to organize commands or options in a hierarchical structure. The Menu and
MenuItem controls are used to create these menus.
Example: Creating a Menu

XML
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Menu Example" Height="300" Width="400">
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_New" Click="New_Click"/>
<MenuItem Header="_Open" Click="Open_Click"/>
<Separator/>
<MenuItem Header="_Exit" Click="Exit_Click"/>
</MenuItem>
<MenuItem Header="_Edit">
<MenuItem Header="_Copy" Click="Copy_Click"/>
<MenuItem Header="_Paste" Click="Paste_Click"/>
</MenuItem>
</Menu>
76

<TextBox Name="mainTextBox" AcceptsReturn="True"


VerticalScrollBarVisibility="Auto" Margin="10"/>
</DockPanel>
</Window>

Csharp

using System.Windows;

namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void New_Click(object sender, RoutedEventArgs e)


{
mainTextBox.Clear();
}

private void Open_Click(object sender, RoutedEventArgs e)


{
MessageBox.Show("Open clicked");
}

private void Exit_Click(object sender, RoutedEventArgs e)


{
Application.Current.Shutdown();
}

private void Copy_Click(object sender, RoutedEventArgs e)


{
mainTextBox.Copy();
}

private void Paste_Click(object sender, RoutedEventArgs e)


{
mainTextBox.Paste();
}
}
}

Output:
A text editor window with a menu containing File and Edit options.
Visual Diagram:
77

 Menu at the top of the window.


 MenuItems for File and Edit actions like New, Open, Exit, Copy, and Paste.
 TextBox for entering and editing text.

5. Commands
Commands encapsulate the logic for actions that can be triggered by controls. WPF uses
the ICommand interface to implement commands, allowing separation of UI and business
logic. Example: Implementing a Simple Command

Csharp

using System;
using System.Windows;
using System.Windows.Input;

namespace WpfApp
{
public partial class MainWindow : Window
{
public ICommand MyCommand { get; set; }

public MainWindow()
{
InitializeComponent();
MyCommand = new RelayCommand(ExecuteMyCommand, CanExecuteMyCommand);
DataContext = this;
}

private void ExecuteMyCommand(object parameter)


{
MessageBox.Show("Command Executed!");
}

private bool CanExecuteMyCommand(object parameter)


{
return true;
}
}
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object, bool>
_canExecute;

public RelayCommand(Action<object> execute, Func<object, bool> canExecute)


{
_execute = execute;
_canExecute = canExecute;
}
78
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}

public void Execute(object parameter)


{
_execute(parameter);
}

public event EventHandler CanExecuteChanged;


}
}

XML
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Command Example" Height="200" Width="300">
<StackPanel>
<Button Content="Click Me" Command="{Binding MyCommand}" Width="100"
Height="30" Margin="10"/>
</StackPanel>
</Window>

Output:
A button that, when clicked, triggers the command and shows a message box.
Visual Diagram:
 Button is bound to a command via the Command property.
 Command Execution shows a message box.

6. Data Binding
Data Binding in WPF is a powerful mechanism that connects the UI to data sources like objects, collections,
or databases. It enables automatic updates of the UI when the underlying data changes.
Example: Simple Data Binding
Csharp
public class Person
{
public string Name { get; set;
} public int Age { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Person { Name = "John Doe", Age = 30 };
}
}
79

XML
<Window x:Class="WpfApp.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="WPF Data Binding Example" Height="200" Width="300">

<StackPanel>

<TextBlock Text="Name:" />

<TextBox Text="{Binding Name}" Width="200" Margin="0,5,0,5"/>

<TextBlock Text="Age:" />

<TextBox Text="{Binding Age}" Width="200" Margin="0,5,0,5"/>

</StackPanel>

</Window>

Output:
A form where the text boxes are automatically populated with data from a Person object.
Visual Diagram:
 DataContext is set to a Person object.
 TextBoxes are bound to properties of the Person object.
80

Unit 5
ASP.NET and ASP.NET Core

5.1. C# and ASP.NET with ASP.NET Core


ASP.NET and ASP.NET Core are both powerful frameworks developed by Microsoft for building
web applications, services, and dynamic websites. ASP.NET is the older, Windows-only framework,
whereas ASP.NET Core is a cross-platform, high-performance, open-source framework designed for
building modern cloud-based applications.
Diagram: ASP.NET vs. ASP.NET Core

Key Features of ASP.NET Core


1. Cross-platform: Runs on Windows, macOS, and Linux.
2. High-performance: Optimized for speed and scalability.
3. Unified Framework: Combines MVC, Web API, and Razor Pages into a single framework.
4. Dependency Injection: Built-in dependency injection for better modularity.
5. Middleware Pipeline: Customizable request pipeline for handling HTTP requests.

Creating a Simple ASP.NET Core Web Application


Step 1: Setting Up the Project
You can create an ASP.NET Core project using Visual Studio, Visual Studio Code, or the .NET CLI.
Here’s how to create a new ASP.NET Core web application using the .NET CLI:
dotnet new webapp -n MyWebApp
This command creates a new ASP.NET Core Web Application in a folder named MyWebApp.

Step 2: Understanding the Project Structure


When you create a new ASP.NET Core project, the structure typically looks like this:
 Program.cs: The entry point of the application. It configures the application and starts the web
server.
 Startup.cs: Configures services and the HTTP request pipeline.
 Pages/: Contains Razor Pages, which are the UI components.
 wwwroot/: Static files like CSS, JavaScript, and images.

Step 3: Writing Code - A Basic "Hello, World!" Example


In ASP.NET Core 6.0 and above, the Program.cs file handles the main configuration and startup of the
application:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
81

var builder = WebApplication.CreateBuilder(args);


var app = builder.Build();

app.MapGet("/", () => "Hello, World!");

app.Run();

Explanation:
 WebApplication.CreateBuilder: Sets up the application with default configurations.
 app.MapGet("/"): Maps the root URL (/) to a simple handler that returns "Hello, World!".
 app.Run(): Runs the application.

Step 4: Running the Application


To run the application, navigate to the project directory and use the following command:
dotnet run
After running the command, navigate to https://localhost:5001/ in your web browser. You will see the
message "Hello, World!" displayed on the screen.

Example: Creating a Simple MVC Application


Let’s create a more complex example using the MVC (Model-View-Controller) pattern.
1. Create a new MVC project:
dotnet new mvc -n MyMvcApp
2. Add a Controller:
Create a HomeController.cs file in the Controllers folder:
using Microsoft.AspNetCore.Mvc;

namespace MyMvcApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET Core
MVC!"; return View();
}
}
}
3. Add a View:
Create a Views/Home/Index.cshtml file:
HTML
@page
@{
ViewData["Title"] = "Home";
}

<h2>@ViewData["Message"]</h2>
82

4. Run the Application:


Navigate to the project directory and run:
dotnet run
Output:
Web Application Output:
 Hello, World!: The output from the first example, displayed when visiting the root URL (/).
 Welcome to ASP.NET Core MVC!: The output from the MVC example, displayed when
visiting the root URL in the MVC application.

5.2. ASP.NET architecture


ASP.NET Architecture is designed to support the development of dynamic web applications by
providing a robust framework for managing requests, responses, and the overall web application
lifecycle. It integrates various components such as the Common Language Runtime (CLR), Base Class
Library (BCL), web server, and different web development models (Web Forms, MVC, Web API,
etc.). ASP.NET Architecture Overview
 ASP.Net is a framework which is used to develop a Web-based application.
 The basic architecture of the ASP.Net framework is as shown below.

The architecture of the.Net framework is based on the following key components


 Language – A variety of languages exists for .net framework. They are VB.net and
C#. These can be used to develop web applications.
 Library – The .NET Framework includes a set of standard class libraries. The most common
library used for web applications in .net is the Web library. The web library has all the necessary
components used to develop.Net web-based applications.
 Common Language Runtime – The Common Language Infrastructure or CLI is a platform. .Net
programs are executed on this platform. The CLR is used for performing key activities. Activities
include Exception handling and Garbage collection.

5.3. Web applications using ASP.NET and ASP.NET MVC


ASP.NET MVC is a framework for building scalable, maintainable, and testable web applications
using the Model-View-Controller (MVC) design pattern. It separates the application into three main
components:
1. Model: Represents the data and business logic of the application.
2. View: Defines how the user interface is presented.
83

3. Controller: Manages user requests, interacts with the model, and renders the appropriate view.
Diagram: MVC Architecture

Key Features of ASP.NET MVC:


 Separation of Concerns: Helps maintain code in separate components (model, view, and
controller).
 Testability: Easy to write unit tests due to the separation of business logic and user interface.
 Full Control over HTML and HTTP: Provides full control over rendering HTML and handling
HTTP requests.

Building a Simple ASP.NET MVC Web Application


In this example, we'll create a simple web application that displays a list of products and allows users
to view product details.

Step 1: Create a New ASP.NET MVC Project


You can create a new ASP.NET MVC project using Visual Studio or the .NET CLI:
dotnet new mvc -n MyMvcApp
This command will create a new ASP.NET MVC project named MyMvcApp.

Step 2: Set Up the Model


Create a Product.cs file in the Models folder to represent a product entity:
namespace MyMvcApp.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set;
}
by Mukesh
} Singh, Sanothimi MICTE (2079/2023 Batch)
84

Step 3: Create the Controller


Create a ProductsController.cs file in the Controllers folder to manage the product-related actions:

using Microsoft.AspNetCore.Mvc;
using MyMvcApp.Models;
using System.Collections.Generic;

namespace MyMvcApp.Controllers
{
public class ProductsController : Controller
{
// Simulating a database with an in-memory list of products
private static readonly List<Product> Products = new
List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99M, Description = "A high-
performance laptop." },
new Product { Id = 2, Name = "Smartphone", Price = 499.99M, Description = "A sleek
smartphone." }
};

// Action to display the list of products


public IActionResult Index()
{
return View(Products);
}

// Action to display the details of a single product


public IActionResult Details(int id)
{
var product = Products.Find(p => p.Id == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
}
}

Step 4: Create the Views


 Index View (List of Products): Create an Index.cshtml file in the Views/Products folder to
display the product list:
@model IEnumerable<MyMvcApp.Models.Product>
<h2>Products</h2>
<table class="table">
<thead>
<tr>
85
<th>Product Name</th>
<th>Price</th>
<th>Details</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model)
{
<tr>
<td>@product.Name</td>
<td>@product.Price.ToString("C")</td>
<td><a href="@Url.Action("Details", new { id = product.Id })">View Details</a></td>
</tr>
}
</tbody>
</table>

Details View (Product Details): Create a Details.cshtml file in the Views/Products folder to display the
product details:

@model MyMvcApp.Models.Product

<h2>@Model.Name</h2>
<p><strong>Price:</strong> @Model.Price.ToString("C")</p>
<p><strong>Description:</strong> @Model.Description</p>

<a href="@Url.Action("Index")">Back to Products List</a>

Step 5: Run the Application


Run the application using the following command:
dotnet run

Now, open a browser and navigate to https://localhost:5001/Products to view the list of products. You
can click on the "View Details" link for any product to see more information.
Output
Index View (List of Products):

Details View (Product Details):


If you click "View Details" for the laptop, you will be directed to:
86

OR

Building Web App With ASP.NET MVC 5


Building a web application with ASP.NET MVC 5 involves a series of steps:

1. Setting Up the Development Environment


To start developing with ASP.NET MVC 5, you’ll need to set up your development environment:
 Install Visual Studio, which is the IDE that supports .NET development. Make sure to
download a version that includes ASP.NET MVC 5 support.
 During installation, select the ASP.NET and web development workload to install all necessary
components for MVC 5 development.

2. Creating Your Project


Once the environment is set up, create a new project:
 Open Visual Studio and select File > New > Project.
 Choose the ASP.NET Web Application (.NET Framework) template.
 Name your project and choose a suitable location for it.
 Click OK and select the MVC template in the next screen.
 Ensure that the authentication is set to No Authentication for now (you can add authentication
later).
 Click Create to generate your project with the necessary folders and files for an MVC
application.

3. Defining the Model


Models are C# classes that represent the data of the application. They can correspond to tables in a
database.
 Create a new model class by right-clicking the Models folder, selecting Add > Class.
 Name your class and add properties that represent the data structure.
If you’re using Entity Framework for data access, you’ll also need to define a DbContext class
within the Models folder.

4. Designing the View


Views contain the HTML markup and content that is sent to the client’s browser. They use the
Razor view engine to embed C# within HTML code.
 Right-click the Views folder corresponding to your controller and select Add > View.
 Name your view and select the template you want to use (e.g., List, Create, Edit).
 You can design your HTML structure and use Razor syntax to display data dynamically.

5. Developing the Controller


Controllers are responsible for handling user input, manipulating models, and selecting views to
render.
 Create a controller by right-clicking the Controllers folder and selecting Add > Controller.
 Choose MVC 5 Controller – Empty.
87

 Name your controller and click Add.


 Implement actions that will respond to user requests.

6. Implementing Security
Security is crucial, and ASP.NET MVC 5 provides several features to secure your applications:
 Use ASP.NET Identity for authentication and authorization.
 Enable SSL in your project to ensure data is encrypted during transit.
 Prevent cross-site scripting (XSS) by encoding HTML outputs.
 Protect against cross-site request forgery (CSRF) using anti-forgery tokens in your forms.

7. Testing and Debugging


Test your application thoroughly:
 Use the Visual Studio debugger to step through your code and identify any issues.
 Write unit tests to verify the logic in your models and controllers.
 Test the user interface and user experience to ensure that views render correctly and the
application flows as intended.
8. Deployment
When you’re ready to deploy:
 Use Visual Studio’s Publish feature to deploy your application to IIS on a local machine or a
remote server.
 Configure your production database and update the connection string in the ‘web.config’ file.
 Make sure to compile your application in Release mode to optimize performance.

By following these steps, you can systematically build a web application using ASP.NET MVC 5,
from initial setup to deployment. There are a few steps to check before, during and after deployment,
which we will talk about below.

5.4. RESTful APIs with ASP.NET Web API


ASP.NET Web API allows you to create RESTful services that can be consumed by different types of
clients (such as browsers, mobile apps, or other servers). A RESTful API in ASP.NET Core Web API
supports operations like Create, Read, Update, and Delete (CRUD).
Steps to Create a RESTful API with ASP.NET Core
1. Create a New ASP.NET Core Web API Project: In Visual Studio or via .NET CLI:

dotnet new webapi -n MyApiApp

2. Define a Model: Create a model class, such as Product.cs, to represent data.


public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set;
}
88

3. Set Up a Controller: Create a ProductsController to handle API requests.


using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private static readonly List<Product> Products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99M, Description = "A high-performance
laptop." },
new Product { Id = 2, Name = "Smartphone", Price = 499.99M, Description = "A sleek
smartphone." }
};

// GET: api/products
[HttpGet]
public ActionResult<IEnumerable<Product>> GetProducts()
{
return Products;
}

// GET: api/products/{id}
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound();
return product;
}

// POST: api/products
[HttpPost]
public ActionResult<Product> CreateProduct(Product product)
{
product.Id = Products.Count + 1;
Products.Add(product);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}

// PUT: api/products/{id}
[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, Product updatedProduct)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound();
89

product.Name = updatedProduct.Name;
product.Price =
updatedProduct.Price;
product.Description =
updatedProduct.Description; return NoContent();
}

// DELETE: api/products/{id}
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound();

Products.Remove(product);
return NoContent();
}
}
4. Test the API Endpoints: You can use tools like Postman or Swagger (built-in to ASP.NET Core
templates) to test each endpoint.

5.5. ASP.NET Core Razor templates


Razor templates in ASP.NET Core are used to dynamically render HTML views using C# code.
Creating a Razor Template
1. Create a Razor Page: Razor templates are typically stored in. cshtml files.
html
@page
@model
MyApp.Pages.IndexModel @{
ViewData["Title"] = "Home Page";
}

<h1>@ViewData["Title"]</h1>
<p>Welcome to the ASP.NET Core Razor page example!</p>

2. Use C# Code: You can insert C# code in Razor pages with the @ symbol.
html
<h2>@DateTime.Now.ToString("yyyy-MM-dd")</h2>

5.6. Razor pages and CRUD Operation


5.7. Authentication and Authorization
5.8. ASP.NET Core middleware
5.9. Deployment (Azure, Docker, AWS)
Explain in details with full coded examples and their outputs.
90

Unit 6
Web Applications with Blazor

6.1. Blazor overview


6.2. Building a web app with Blazor: UI, Components, Data binding, data sharing, events and event
handlings
6.3. Blazor pages, layouts, routing, navigation
6.4. Reusable Blazor components using Layouts
6.5. DOM events with Blazor event handlers
6.6. Server-side and client-side validation to the form
6.7. Application interactivity with lifecycle events
6.8. Razor class library concept and creation.

Unit 7
Cross-Platform Development with Xamarin

7.1. Overview of Xamarin and Cross-Platform Development


7.2. MVC and MVVM design patterns for Cross-Platform Development
7.3. XAML Basics: Layouts, Controls, Text, Data bindings, Styles and Graphics
7.4. XAML and Xamarin
7.5. Xamarin vs Xamarin.Forms
7.6. Xamarin Form Controls: Layout, Page, Views, Cells
7.7. Navigation: Patterns, Modal Views, Drill-downs, Tabbed views, Master-Detail views.
7.8. User Interface (Styles, Navigations, Maps, ListView) and Themes (Light, Dark and Custom build)
7.9. Working with SQLite.NET database
7.10. Android Development with Xamarin: Creating views, Calling Services, OAuth 2.
7.11. Deploying application

You might also like