0% found this document useful (0 votes)
3 views16 pages

CSharp NET Complete Notes

The document provides comprehensive study notes for the ITA205 C# and .NET Programming course at Puducherry Technological University, covering key concepts such as the .NET Framework, C# language features, object-oriented programming principles, and advanced topics like interfaces, delegates, and exception handling. It includes detailed explanations of data types, control structures, inheritance, and threading, along with examples and comparisons between structures and classes. The course is structured into units that facilitate a progressive understanding of C# programming and its applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

CSharp NET Complete Notes

The document provides comprehensive study notes for the ITA205 C# and .NET Programming course at Puducherry Technological University, covering key concepts such as the .NET Framework, C# language features, object-oriented programming principles, and advanced topics like interfaces, delegates, and exception handling. It includes detailed explanations of data types, control structures, inheritance, and threading, along with examples and comparisons between structures and classes. The course is structured into units that facilitate a progressive understanding of C# programming and its applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ITA205 – C# and .

NET Programming
Complete Study Notes
Department Information Technology
Semester Sixth
Course Code ITA205
University Puducherry Technological University
Credits 3 | CA: 25 | SE: 75 | Total: 100
Units Covered I · II · III · IV · V

Perunthalivar Kamarajar Institute of Engineering & Technology, Karaikal

ITA205 – C# and .NET Programming | PKIET Page 1


UNIT I – Introduction to C#
This unit covers the basics of C#, the .NET Framework, data types, control structures, arrays, and OOP
fundamentals.

1.1 Introduction to .NET Framework


.NET (pronounced "dot net") is a free, open-source, cross-platform developer platform created by Microsoft. It is
used to build many different types of applications — web, mobile, desktop, games, IoT, and more. The .NET
Framework is a software development framework for building and running applications on Windows.

Key Advantages of .NET:


• Language Interoperability – Multiple languages (C#, [Link], F#) share a common runtime
• Common Language Runtime (CLR) – Manages memory, type safety, exception handling, and security
• Extensive Class Library (BCL) – Provides reusable classes for file I/O, networking, data access, etc.
• Platform Independence – .NET Core/.NET 5+ runs on Windows, Linux, and macOS
• Automatic Memory Management – Garbage Collector (GC) handles memory allocation/deallocation
• Security – CAS (Code Access Security) and role-based security built-in
• Versioning – Allows side-by-side execution of different versions

1.2 .NET Architecture


The .NET architecture consists of three major layers:

<b>Layer</b> <b>Component</b> <b>Description</b>

Programming Languages
Top Source code is written in any .NET-compatible language
(C#, [Link], F#)

Common Language
Middle Compiles source to CIL (Common Intermediate Language) / MSIL
Infrastructure (CLI)

CLR (Common Language


Bottom JIT compiles CIL to native machine code and executes it
Runtime)

CLR Components:
• JIT Compiler – Converts CIL to native code at runtime
• Garbage Collector (GC) – Automatic memory management
• Type Checker – Ensures type safety
• Exception Manager – Handles runtime exceptions
• Thread Support – Manages threads and synchronization
• Security Engine – Enforces security policies

1.3 Overview of C#
C# (pronounced "C sharp") is a modern, object-oriented, type-safe programming language developed by Microsoft.
It was designed by Anders Hejlsberg and first appeared in 2000. C# is part of the .NET ecosystem and compiles to
CIL.

Features of C#:
• Object-Oriented – Supports classes, objects, inheritance, polymorphism, encapsulation
• Type-Safe – Prevents unsafe type casts and undefined behavior

ITA205 – C# and .NET Programming | PKIET Page 2


• Garbage Collected – Automatic memory management via CLR GC
• Strongly Typed – Every variable must be declared with a type
• Component-Oriented – Supports properties, events, attributes
• Versioning – Designed for easy version management
• Unified Type System – All types (value + reference) derive from object

1.4 C# Literals, Variables, and Data Types


<b>Category</b> <b>Type</b> <b>Size</b> <b>Range / Example</b>

Integer int 4 bytes -2,147,483,648 to 2,147,483,647

Integer long 8 bytes -9.2×10^18 to 9.2×10^18

Integer short 2 bytes -32,768 to 32,767

Integer byte 1 byte 0 to 255

Float float 4 bytes ±3.4×10^38 (7 digits precision)

Float double 8 bytes ±1.7×10^308 (15-16 digits)

Float decimal 16 bytes 28-29 significant digits (financial)

Text char 2 bytes Single Unicode character

Text string Variable Sequence of Unicode characters

Boolean bool 1 byte true or false

Object object Variable Base type of all types

Boxing and Unboxing:


Boxing is the process of converting a value type (int, float, etc.) to a reference type (object). Unboxing is the
reverse process of extracting the value type back from the object.
int x = 42; object obj = x; // Boxing – value type → reference type int y = (int)obj; // Unboxing
– reference type → value type

Boxing involves heap allocation (slower). Unboxing requires explicit cast and throws InvalidCastException if types
don't match.

1.5 Arrays and Array Class


An array is a fixed-size, sequential collection of elements of the same type stored in contiguous memory.
// Single-dimensional int[] marks = new int[5]; int[] scores = {90, 85, 78, 92, 88}; //
Multi-dimensional int[,] matrix = new int[3,3]; // Jagged Array (array of arrays) int[][] jagged =
new int[3][]; jagged[0] = new int[] {1, 2}; jagged[1] = new int[] {3, 4, 5}; jagged[2] = new int[]
{6};

Jagged Array:
A jagged array is an array of arrays where each sub-array can have a different length. This is useful when rows
have variable column counts. Advantages: Memory efficient; flexible row sizes.

1.6 C# Structure (struct)


A structure is a value type that can contain data members and methods. Unlike classes, structs are stored on the
stack (when declared as local variables), making them faster for small data.
struct Student { public int RollNo; public string Name; public float CGPA; } // Usage: Student s;
[Link] = 1; [Link] = "Leo"; [Link] = 9.1f;

ITA205 – C# and .NET Programming | PKIET Page 3


Structure vs Class:
<b>Feature</b> <b>Struct</b> <b>Class</b>

Type Value type Reference type

Storage Stack Heap

Inheritance Not supported Supported

Default constructor Cannot be defined Can be defined

Performance Faster (small data) Slightly slower

Nullability Cannot be null Can be null

1.7 Enumerations
An enum is a value type that defines a set of named integer constants. It improves code readability.
enum Day { Sun=0, Mon, Tue, Wed, Thu, Fri, Sat } Day today = [Link];
[Link]((int)today); // Output: 1

1.8 Inheritance in C#
Inheritance allows a class (derived/child) to acquire properties and methods of another class (base/parent). C#
supports single inheritance for classes and multiple inheritance through interfaces.
class Animal { public string Name; public void Eat() { [Link](Name + " is eating"); } }
class Dog : Animal { // Dog inherits Animal public void Bark() { [Link]("Woof!"); } }
// Multilevel Inheritance class Puppy : Dog { public void Play() { [Link]("Playing!");
} }

Types of Inheritance:
• Single – One base, one derived class
• Multilevel – Chain of inheritance (A → B → C)
• Hierarchical – One base, multiple derived classes
• Multiple – Achieved through interfaces only in C#

Student Grade Program using Multilevel Inheritance:


class Student { public string Name; public int Roll; public void Display() {
[Link]($"Roll:{Roll}, Name:{Name}"); } } class Marks : Student { public int M1, M2, M3;
public int Total() { return M1+M2+M3; } } class Grade : Marks { public string GetGrade() { float
avg = Total() / 3.0f; if (avg >= 90) return "O"; else if (avg >= 75) return "A"; else if (avg >=
60) return "B"; else return "C"; } } // Main: Grade g = new Grade(); [Link] = "Leo"; [Link] = 1;
g.M1 = 92; g.M2 = 88; g.M3 = 95; [Link](); [Link]($"Total:{[Link]()},
Grade:{[Link]()}");

ITA205 – C# and .NET Programming | PKIET Page 4


UNIT II – Object-Oriented Aspects of C#
This unit covers advanced OOP concepts: classes, objects, constructors, properties, indexers, polymorphism,
interfaces, delegates, events, and exception handling.

2.1 Classes and Objects


A class is a blueprint/template for creating objects. An object is an instance of a class. Classes encapsulate data
(fields) and behavior (methods).
class BankAccount { private string owner; private double balance; public BankAccount(string name,
double bal) { owner = name; balance = bal; } public void Deposit(double amt) { balance += amt; }
public void Withdraw(double amt) { if (amt <= balance) balance -= amt; else
[Link]("Insufficient funds"); } public void Display() { [Link]($"Owner:
{owner}, Balance: {balance:F2}"); } }

2.2 Constructors and Its Types


<b>Type</b> <b>Description</b> <b>Example</b>

Default No parameters, auto-created if none defined public MyClass() {}

Parameterized Takes arguments for initialization public MyClass(int x) {}

Copy Creates a copy of an existing object public MyClass(MyClass obj) {}

Static Called once; initializes static members static MyClass() {}

Private Used in Singleton pattern private MyClass() {}

2.3 Properties
Properties provide a flexible mechanism to read, write, or compute the value of a private field. They use get and
set accessors.
class Person { private int _age; public int Age { get { return _age; } set { if (value >= 0 &&
value <= 150) _age = value; else throw new ArgumentException("Invalid age"); } } //
Auto-implemented property public string Name { get; set; } }

2.4 Indexers
Indexers allow objects to be indexed like arrays. They use the this keyword with parameters.
class StudentMarks { private int[] marks = new int[5]; public int this[int index] { get { return
marks[index]; } set { marks[index] = value; } } } // Usage: StudentMarks sm = new StudentMarks();
sm[0] = 90; sm[1] = 85; [Link](sm[0]); // 90

Indexers vs Properties:
<b>Feature</b> <b>Indexer</b> <b>Property</b>

Identifier Uses this keyword Has a name

Access obj[index] [Link]

Parameters Can have parameters No parameters

Use case Array-like access Single value access

2.5 Polymorphism

ITA205 – C# and .NET Programming | PKIET Page 5


Polymorphism means "many forms." It allows methods to behave differently based on the object type. C# supports
two types:
• Compile-time (Static) Polymorphism – Method overloading, operator overloading
• Runtime (Dynamic) Polymorphism – Method overriding using virtual/override keywords
class Shape { public virtual double Area() { return 0; } } class Circle : Shape { double r; public
Circle(double r) { this.r = r; } public override double Area() { return [Link] * r * r; } } class
Rectangle : Shape { double w, h; public Rectangle(double w, double h) { this.w=w; this.h=h; }
public override double Area() { return w * h; } } // Runtime polymorphism: Shape s = new Circle(5);
[Link]([Link]()); // 78.54...

2.6 Interface
An interface is a contract that defines a set of method signatures without implementation. Classes implement
interfaces using the : symbol. Interfaces support multiple inheritance.
interface IBankOps { void Deposit(double amount); void Withdraw(double amount); double
GetBalance(); } interface IAccountInfo { void DisplayInfo(); } class SavingsAccount : IBankOps,
IAccountInfo { private double balance; private string owner; public SavingsAccount(string name,
double bal) { owner = name; balance = bal; } public void Deposit(double amount) { balance +=
amount; } public void Withdraw(double amount) { if (amount <= balance) balance -= amount; } public
double GetBalance() { return balance; } public void DisplayInfo() { [Link]($"Owner:
{owner}, Balance: ■{balance:F2}"); } }

Abstract Class vs Interface:


<b>Feature</b> <b>Abstract Class</b> <b>Interface</b>

Implementation Can have method bodies No method bodies (C# 7)

Inheritance Single inheritance only Multiple interfaces allowed

Fields Can have fields No fields

Constructors Can have constructors Cannot have constructors

Access modifier Can use any All members public by default

Use when Shared base behavior Defining a contract/capability

2.7 Sealed Class and Methods


A sealed class cannot be inherited. A sealed method cannot be overridden in derived classes. This prevents
unintended modification.
sealed class Constants { public const double PI = 3.14159; public const double E = 2.71828; } //
Constants cannot be derived: class MyConst : Constants { } // ERROR

2.8 Delegates
A delegate is a type-safe function pointer that holds references to methods with a specific signature. Delegates are
used extensively in event handling and callback mechanisms.
// Declare a delegate delegate int MathOp(int a, int b); class Calculator { public static int
Add(int a, int b) { return a + b; } public static int Multiply(int a, int b) { return a * b; } } //
Usage: MathOp op = [Link]; [Link](op(5, 3)); // 8 op = [Link];
[Link](op(5, 3)); // 15 // Multicast delegate op += [Link]; // Both methods
chained

2.9 Events

ITA205 – C# and .NET Programming | PKIET Page 6


Events are based on delegates and implement the publisher-subscriber pattern. A class (publisher) raises events;
other classes (subscribers) handle them.
class Button { public delegate void ClickHandler(object sender, EventArgs e); public event
ClickHandler Click; public void OnClick() { Click?.Invoke(this, [Link]); } } class Form {
public Form() { Button btn = new Button(); [Link] += HandleClick; // Subscribe } void
HandleClick(object s, EventArgs e) { [Link]("Button was clicked!"); } }

2.10 Exception Handling


C# uses structured exception handling with try, catch, finally, and throw keywords.
try { int[] arr = {1,2,3}; [Link](arr[5]); // IndexOutOfRangeException } catch
(IndexOutOfRangeException ex) { [Link]("Array index error: " + [Link]); } catch
(Exception ex) { [Link]("General error: " + [Link]); } finally {
[Link]("This always executes – cleanup here"); }

Common Exception Classes:


<b>Exception</b> <b>Cause</b>

NullReferenceException Accessing a null object reference

IndexOutOfRangeException Array index out of bounds

DivideByZeroException Division by zero

InvalidCastException Invalid type casting

FileNotFoundException File does not exist

OverflowException Arithmetic overflow in checked context

SqlException SQL Server database error

OutOfMemoryException Insufficient memory

2.11 Threading
Threading enables concurrent execution of multiple operations. The [Link] namespace provides
Thread, ThreadPool, and synchronization primitives.
using [Link]; class Demo { static void PrintNumbers() { for (int i = 1; i <= 5; i++) {
[Link]($"Thread: {i}"); [Link](100); } } static void Main() { Thread t = new
Thread(PrintNumbers); [Link](); [Link]("Main thread continues..."); [Link](); // Wait
for thread to finish } }

ITA205 – C# and .NET Programming | PKIET Page 7


UNIT III – Application Development on .NET
This unit covers Windows Forms development, SDI/MDI applications, Dialog Boxes, and [Link] for database
access.

3.1 SDI and MDI Applications


Windows Forms applications can be of two types based on how documents are managed:

<b>Feature</b> <b>SDI (Single Document Interface)</b>


<b>MDI (Multiple Document Interface)</b>

Documents open One at a time Multiple simultaneously

Window structure Single window Parent + multiple child windows

Example apps Notepad, Paint Visual Studio, Microsoft Word

Resource usage Less More

User experience Simple Complex, more productive

Creating MDI Application:


// Parent (MDI Container) Form: [Link] = true; [Link] = "MDI Application"; //
Opening a child window: private void OpenChild() { ChildForm child = new ChildForm();
[Link] = this; // Link to MDI parent [Link](); }

3.2 Dialog Boxes – Modal and Modeless


Dialog boxes are special windows used to interact with the user for specific tasks.
<b>Type</b> <b>Modal Dialog</b> <b>Modeless Dialog</b>

Blocks parent? Yes – parent disabled until closed No – parent remains active

Display method ShowDialog() Show()

Return value DialogResult enum No return value

Example Login prompt, Save dialog Find & Replace in Word

// Modal dialog: LoginDlg dlg = new LoginDlg(); if ([Link]() == [Link]) { string


user = [Link]; string pass = [Link]; // process login } // Modeless dialog: FindDialog
find = new FindDialog(); [Link](); // Parent continues to work

3.3 [Link] – Introduction


[Link] (ActiveX Data Objects for .NET) is a data access technology that provides a set of classes for
communicating with data sources like SQL Server, Oracle, MySQL, XML files, etc. It is part of the [Link]
namespace.

[Link] Core Objects:


<b>Object</b> <b>Purpose</b>

SqlConnection Establishes connection to SQL Server database

SqlCommand Executes SQL queries or stored procedures

SqlDataReader Reads data in forward-only, read-only stream

SqlDataAdapter Bridges DataSet and database; fills and updates data

ITA205 – C# and .NET Programming | PKIET Page 8


DataSet In-memory, disconnected representation of data (multiple tables)

DataTable Single in-memory table with rows and columns

DataView Customizable view of a DataTable (filter, sort)

3.4 Accessing Data with [Link]


Step-by-step process to read data from a SQL Server database:
using System; using [Link]; using [Link]; string connStr = "Data
Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI"; SqlConnection conn = new
SqlConnection(connStr); SqlDataReader rdr = null; try { [Link](); // Step 1: Open connection //
Step 2: Create command SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); // Step
3: Execute reader rdr = [Link](); // Step 4: Read data while ([Link]()) {
[Link]($"{rdr["CustomerID"]} – {rdr["CompanyName"]}"); } } finally { if (rdr != null)
[Link](); if (conn != null) [Link](); }

3.5 DataSet and SqlDataAdapter (Disconnected Model)


The DataSet operates in disconnected mode – connection is opened only to fill or update data, then closed. This
improves scalability.
SqlConnection conn = new SqlConnection(connStr); DataSet ds = new DataSet(); // Create DataAdapter
with SELECT query SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customers", conn); //
Auto-generate INSERT/UPDATE/DELETE commands SqlCommandBuilder cb = new SqlCommandBuilder(da); //
Fill DataSet (connection opens/closes automatically) [Link](ds, "Customers"); // Bind to DataGrid
[Link] = ds; [Link] = "Customers"; // Update changes back to database
[Link](ds, "Customers");

3.6 Stored Procedures with [Link]


A stored procedure is a precompiled SQL block stored on the database server. Using them improves performance
and security.
using (SqlConnection conn = new SqlConnection(connStr)) { SqlCommand cmd = new
SqlCommand("GetEmployees", conn); [Link] = [Link]; // Add parameter
if needed [Link]("@DeptID", 10); [Link](); using (SqlDataReader rdr =
[Link]()) { while ([Link]()) { [Link]($"ID:{rdr["EmpID"]},
Name:{rdr["Name"]}"); } } }

3.7 Exception Handling in [Link]


try { using (SqlConnection conn = new SqlConnection(connStr)) { [Link](); // DB operations here
} } catch (SqlException ex) { [Link]("SQL Error: " + [Link]);
[Link]("Error Number: " + [Link]); } catch (Exception ex) {
[Link]("General Error: " + [Link]); } finally { // Cleanup (connections auto-closed
with using statement) [Link]("Operation complete"); }

3.8 SQL Server with [Link]


SQL Server is the primary RDBMS used with [Link]. The [Link] namespace provides SQL
Server-specific data provider classes.

Connection String Parameters:


<b>Parameter</b> <b>Description</b> <b>Example</b>

Data Source Server name/IP "(local)" or "[Link]"

ITA205 – C# and .NET Programming | PKIET Page 9


Initial Catalog Database name "Northwind"

Integrated Security Windows authentication "SSPI" or "True"

User ID SQL Server username "sa"

Password SQL Server password "mypass"

Connect Timeout Wait time in seconds "30"

3.9 Validating Controls in [Link] / [Link]


[Link] provides built-in validation controls to validate user input before it reaches the server.

<b>Validator</b> <b>Purpose</b> <b>Example</b>

RequiredFieldValidator Ensures field is not empty Username must be filled

RangeValidator Checks value is in a range Age between 18-60

RegularExpressionValidator Validates against a pattern Email format check

CompareValidator Compares two fields Password == Confirm Password

CustomValidator Custom validation logic Check DB for duplicate username

ValidationSummary Shows all errors in one place Error list at top of form

ITA205 – C# and .NET Programming | PKIET Page 10


UNIT IV – Web-Based Application Development on .NET
This unit covers [Link] Web Forms, Web Services (SOAP/WSDL/UDDI), XML with .NET, session
management, and dataset passing.

4.1 [Link] – Introduction


[Link] is a web application framework developed by Microsoft to build dynamic web applications and services.
It is part of the .NET platform and supports multiple programming models.

[Link] Programming Models:


• Web Forms – Drag-and-drop, event-driven model (like Windows Forms for web)
• [Link] MVC – Model-View-Controller pattern; clean separation of concerns
• [Link] Web Pages – Lightweight, Razor syntax for single-page apps
• [Link] Web API – RESTful web services
• [Link] Core – Cross-platform, open-source, modern redesign of [Link]

4.2 Programming Web Applications with Web Forms


[Link] Web Forms provides an event-driven model for building web applications. Pages are requested by the
browser and processed on the server which returns HTML.

Key Features of Web Forms:


• Server Controls – Pre-built UI elements (TextBox, Button, GridView, etc.)
• Master Pages – Consistent layout template shared across pages
• Code-Behind – Separates UI (ASPX) from logic (CS/VB files)
• ViewState – Preserves page state between postbacks
• Data Binding – Easy binding of data sources to controls
• Event Handling – Server-side event handlers (Button_Click, etc.)

[Link] Page Lifecycle:


1. Page Request → IIS receives the request
2. Start → Page properties set (Request, Response)
3. Initialization → Controls initialized, UniqueID set
4. Load → Page_Load event fires; ViewState restored
5. Postback Event Handling → Button_Click, etc. execute
6. Rendering → Page writes HTML to output stream
7. Unload → Cleanup, objects disposed

4.3 Working with XML and .NET


The [Link] namespace provides rich classes for creating, reading, and manipulating XML documents.

<b>Class</b> <b>Purpose</b>

XmlDocument DOM-based; loads entire XML into memory for read/write

XmlTextReader Forward-only, fast streaming XML reader

XmlTextWriter Writes XML to a stream or file

XmlValidatingReader Validates XML against XSD schema

ITA205 – C# and .NET Programming | PKIET Page 11


XDocument (LINQ) Modern LINQ-to-XML API for querying XML

XmlSerializer Serializes/deserializes objects to/from XML

4.4 Creating Virtual Directory and Web Application (IIS)


Internet Information Services (IIS) is Microsoft's web server that hosts [Link] applications. Steps to deploy an
[Link] app on IIS:
1. Build the project in Visual Studio → Publish to a folder
2. Install IIS (Control Panel → Windows Features → IIS)
3. Copy published files to C:\inetpub\wwwroot\YourAppFolder
4. Open IIS Manager → Right-click Sites → Add Website
5. Set Physical Path to your app folder
6. Assign hostname and port (e.g., [Link], port 80)
7. Edit Hosts file (C:\Windows\System32\drivers\etc\hosts) to map IP to hostname
8. Start the website and browse to it

4.5 State Management in [Link]


HTTP is stateless by nature. [Link] provides techniques to persist data across requests.

<b>Technique</b> <b>Storage</b> <b>Scope</b> <b>Best For</b>

ViewState Hidden field in page Single page Form data between postbacks

Session State Server memory/DB User session Login info, shopping cart

Application State Server memory All users Hit counter, global config

Cookies Client browser User browser Preferences, session tokens

Query String URL parameters Per request Non-sensitive data (ProductID)

Cache Server memory Configurable Frequently accessed data

Hidden Fields HTML hidden input Single page Non-sensitive temporary data

// Session State: Session["Username"] = "Leo"; // Store string user = (string)Session["Username"];


// Retrieve // Application State: Application["Visitors"] = 100; int count =
(int)Application["Visitors"]; // Cookie: HttpCookie cookie = new HttpCookie("Theme"); [Link]
= "Dark"; [Link] = [Link](30); [Link](cookie); // Query
String: [Link]("[Link]?id=42"); string id = [Link]["id"];

4.6 Web Services


A Web Service is a software component that enables communication between different applications over the
internet using standard protocols (HTTP, XML, SOAP).

Web Service Technologies:


<b>Technology</b>
<b>Full Form</b> <b>Purpose</b>

SOAP Simple Object Access Protocol XML-based message format for web service communication

WSDL Web Service Description Language Describes the web service interface (methods, parameters, types)

UDDI Universal Description Discovery Integration


Directory for discovering web services

HTTP HyperText Transfer Protocol Transport protocol for web service messages

XML eXtensible Markup Language Data format for messages (language/platform independent)

ITA205 – C# and .NET Programming | PKIET Page 12


Creating a Web Service:
[WebService(Namespace = "[Link] [WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)] public class MathService : [Link] {
[WebMethod] public int Add(int n1, int n2) { return n1 + n2; } [WebMethod] public int Subtract(int
n1, int n2) { return n1 - n2; } [WebMethod] public int Multiply(int n1, int n2) { return n1 * n2; }
}

4.7 Passing and Returning Datasets from Web Services


[Link] DataSets can be passed through Web Services because they serialize to XML natively. This enables
truly disconnected distributed applications.
// Web Service returning a DataSet: [WebMethod] public DataSet GetStockData() { string connStr =
"Data Source=MyServer;...;"; SqlConnection conn = new SqlConnection(connStr); string sql = "SELECT
* FROM Stock"; SqlDataAdapter da = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet();
[Link](ds, "stock"); return ds; // [Link] auto-serializes to XML } // Client consuming the web
service: MyService.Service1 svc = new MyService.Service1(); DataSet ds = [Link]();
[Link](ds, "stock");

4.8 Exceptions from SQL Server in Web Services


try { // web service DB operation [Link](); [Link](); } catch (SqlException sqlEx)
{ // Return meaningful error via web service throw new SoapException( "Database error: " +
[Link], [Link]); }

ITA205 – C# and .NET Programming | PKIET Page 13


UNIT V – CLR and .NET Framework
This unit covers assemblies, versioning, reflection, security in .NET, attributes, and the .NET security architecture.

5.1 Assemblies
An assembly is the fundamental unit of deployment, version control, reuse, activation scoping, and security
permissions in .NET. Assemblies are compiled outputs (DLL or EXE) that contain:
• MSIL code – Microsoft Intermediate Language (compiled from C#)
• Metadata – Type information, member descriptions
• Manifest – Assembly identity, version, culture, referenced assemblies
• Resources – Images, strings, localization data (optional)

Types of Assemblies:
<b>Type</b> <b>Description</b> <b>Storage</b>

Private Assembly Used by a single application only Application directory

Shared Assembly Used by multiple applications; stored in GAC Global Assembly Cache (GAC)

Satellite Assembly Contains culture-specific resources for localization


Subfolder by culture code

Single-file Assembly All code in one .dll or .exe Single file

Multi-file Assembly Multiple modules compiled together Multiple files

5.2 Versioning in .NET


.NET supports side-by-side execution – multiple versions of the same assembly can coexist and run
simultaneously. The assembly version number has four parts:
[assembly: AssemblyVersion("[Link]")] // Example: [assembly:
AssemblyVersion("[Link]")] // Major – Breaking changes // Minor – New features (backward
compatible) // Build – Build number // Revision – Bug fixes/patches

5.3 Attributes in .NET


Attributes are declarative tags that add metadata to code elements (classes, methods, properties, etc.). They are
enclosed in square brackets [].
// Common built-in attributes: [Obsolete("Use NewMethod() instead")] // Marks method as deprecated
public void OldMethod() { } [Serializable] // Marks class as serializable public class Employee {
} [DllImport("[Link]")] // Import unmanaged DLL public static extern int MessageBox(...); //
Custom attribute: [AttributeUsage([Link] | [Link])] public class
AuthorAttribute : Attribute { public string Name { get; } public AuthorAttribute(string name) {
Name = name; } } [Author("Leo")] class MyClass { }

5.4 Reflection
Reflection is the ability of a program to examine and modify its own structure and behavior at runtime. The
[Link] namespace provides types for reading metadata.
using [Link]; // Get type information: Type t = typeof(string);
[Link]("Type: " + [Link]); [Link]("Namespace: " + [Link]); // List all
methods: MethodInfo[] methods = [Link](); foreach (var m in methods) {
[Link]([Link]); } // Invoke method dynamically: Type calcType = typeof(Calculator);
object obj = [Link](calcType); MethodInfo addMethod = [Link]("Add");
int result = (int)[Link](obj, new object[] { 5, 3 }); [Link](result); // 8

ITA205 – C# and .NET Programming | PKIET Page 14


Uses of Reflection:
• Dynamic loading of assemblies at runtime
• Viewing type metadata (type discovery)
• Creating instances dynamically using [Link]()
• Invoking methods at runtime without compile-time knowledge
• Building object mappers, serializers, and ORMs
• Plugin/extensibility systems
• Unit testing frameworks (finding test methods)

5.5 Security in .NET


.NET provides a comprehensive security architecture with multiple layers of protection.

Security Mechanisms:
<b>Mechanism</b> <b>Description</b>

Code Access Security (CAS) Grants or denies permissions based on code's origin (internet, intranet, local)

Role-Based Security (RBS) Controls access based on user's role (Admin, User, Guest)

Cryptography Provides encryption/decryption using AES, RSA, SHA algorithms

Windows Authentication Uses Windows login credentials for authentication

Forms Authentication Custom login page with session-based authentication ([Link])

Principal & Identity IPrincipal/IIdentity interfaces represent current user

Secure Sockets (SSL/TLS) Encrypts data in transit using HTTPS

// Role-Based Security: using [Link]; WindowsIdentity identity =


[Link](); WindowsPrincipal principal = new WindowsPrincipal(identity); if
([Link]([Link])) { [Link]("User is
Administrator"); } else { [Link]("Access Denied"); }

5.6 Versioning and Attributes Summary


Assembly attributes provide metadata about the assembly. They are placed in [Link]:
[assembly: AssemblyTitle("MyApp")] [assembly: AssemblyDescription("Sample .NET Application")]
[assembly: AssemblyCompany("Microlabs")] [assembly: AssemblyProduct("MyApp v1.0")] [assembly:
AssemblyCopyright("© 2025 Microlabs")] [assembly: AssemblyVersion("[Link]")] [assembly:
AssemblyFileVersion("[Link]")]

QUICK EXAM REFERENCE

Frequently Asked 2-Mark Questions & Answers


Q: What are the advantages of .NET?
A: Language interoperability, CLR (garbage collection, type safety), large BCL, platform independence (Core),
security (CAS, RBS), versioning support.

Q: Define Indexer and its uses.


A: An indexer allows objects to be indexed like arrays using the "this" keyword with parameters. Used to access
elements within a collection class using bracket notation: obj[i].

ITA205 – C# and .NET Programming | PKIET Page 15


Q: State the uses of Windows Forms.
A: Creating desktop GUI applications; supports controls (buttons, textboxes), menus, dialogs, MDI, event handling,
and data binding.

Q: What are the advantages of [Link]?


A: Server-side processing, event-driven model, rich server controls, separation of UI and logic, built-in state
management, security, and scalability.

Q: Define Assemblies.
A: An assembly is the fundamental deployment unit in .NET containing MSIL, metadata, manifest, and resources.
It can be a DLL or EXE.

Q: Define Boxing and Unboxing.


A: Boxing converts a value type to a reference type (object). Unboxing extracts the value type from the object.
Boxing causes heap allocation.

Q: What is [Link]?
A: [Link] is a data access technology in .NET for interacting with databases. Key objects: SqlConnection,
SqlCommand, SqlDataReader, SqlDataAdapter, DataSet.

Q: What is a Delegate?
A: A delegate is a type-safe function pointer that holds a reference to a method with a specific signature. Used for
callbacks, events, and multicast operations.

Q: Differentiate SDI and MDI.


A: SDI allows one document at a time (e.g., Notepad). MDI allows multiple child windows inside a parent window
(e.g., Visual Studio).

Q: What is Reflection?
A: Reflection allows inspection of type metadata at runtime. Used for dynamic method invocation, type discovery,
and building extensible systems.

Key Formulas and Patterns


// [Link] Pattern: SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd = new
SqlCommand(sql, conn); [Link](); SqlDataReader rdr = [Link](); while ([Link]()) {
/* read data */ } [Link](); [Link](); // Exception Handling Pattern: try { /* risky code */
} catch (SqlException ex) { /* handle SQL errors */ } catch (Exception ex) { /* handle other errors
*/ } finally { /* cleanup */ } // Delegate + Event Pattern: public delegate void Handler(object s,
EventArgs e); public event Handler MyEvent; private void OnEvent() { MyEvent?.Invoke(this,
[Link]); } // Stored Procedure Pattern: [Link] = [Link];
[Link] = "ProcName"; [Link]("@Param", value);

— End of Notes —

ITA205 C# and .NET Programming | PKIET, Karaikal | PTU

ITA205 – C# and .NET Programming | PKIET Page 16

You might also like