Label: This guide is built from the mapped archived 2018 TOC for CACS302 (mapped course code BCA405-I), located at the course outline. It preserves every source unit and topic in order. It is NOT a new 2025 detailed syllabus and does not claim official 2025 status.
Course overview
Dotnet Technology teaches programming with the .NET framework and C# for enterprise applications. Students learn object orientation, type safety, memory management, the CLR and .NET Framework, C# language basics (types, statements, namespaces), creating types (classes, properties, indexers, inheritance, interfaces, generics), and advanced C# (delegates, events, lambdas, exceptions, LINQ, databases, ASP.NET web applications). Class load: 6 hrs/week (Theory 3, Practical 3), 3 credits.
Learning outcomes (derived only from the approved TOC)
By the end of this course, a student should be able to:
- Explain object orientation, type safety, memory management, and platform support in .NET.
- Describe C# and CLR, CLR and .NET Framework, other frameworks, framework overview, and .NET Standard 2.0.
- Write console and GUI applications; use identifiers, keywords, comments, data types, expressions, operators, strings, characters, arrays, variables, parameters, statements, and namespaces.
- Create classes, constructors/deconstructors, use the this reference, properties, indexers, static constructors/classes, finalizers, dynamic binding, operator overloading, inheritance, abstract classes/methods, the base keyword, overloading, object type, structs, access modifiers, interfaces, enums, and generics.
- Use delegates, events, lambda expressions, exception handling, LINQ, work with databases, and write web applications using ASP.NET.
Unit 1: Introducing C# and the .NET Framework
Teaching hours: 7
Topics in outline order
- Object Orientation
- Type Safety
- Memory Management
- Platform Support
- C# and CLR
- CLR and .NET Framework
- Other Frameworks
- Framework Overview
- .NET Standard 2.0
- Applied Technologies
1. Object Orientation
Plain-language definition and why it matters. Object orientation (OOP) models software as objects that combine data (fields) and behavior (methods). It matters because C# and .NET are fundamentally object-oriented; most .NET code is written as classes and objects.
Core theory. Four pillars: encapsulation (hide data, expose via methods/properties), inheritance (reuse code by deriving classes), polymorphism (one interface, many forms — method overriding/overloading), abstraction (hide complexity, show essentials). Class = blueprint; object = instance. Members: fields, properties, methods, events, constructors. Access modifiers control visibility.
Syntax / notation. C# class:
public class Account
{
private decimal balance; // encapsulated field
public decimal Balance => balance; // property
public void Deposit(decimal amount) => balance += amount;
}
Worked example.
public class Customer
{
public string Name { get; set; } // auto-property
public void Greet() => System.Console.WriteLine($"Hello, {Name}");
}
// usage
var c = new Customer { Name = "Sita" };
c.Greet(); // Hello, Sita
Realistic use case. An enterprise HR system models Employee, Department, and Payroll as classes with inheritance (FullTimeEmployee : Employee).
Comparison table.
| Pillar | Meaning | Example |
|---|---|---|
| Encapsulation | hide internal state | private field + public property |
| Inheritance | derive from a base class | Manager : Employee |
| Polymorphism | same call, different behavior | virtual method overridden |
| Abstraction | hide complexity | abstract class/interface |
Common mistakes / limitations. Exposing fields directly (breaks encapsulation); deep inheritance hierarchies (fragile); treating structs like classes (structs are value types).
Exam-ready answer points. Define OOP; list the four pillars with examples; distinguish class vs object.
Self-check questions with answers.
- What is encapsulation? Answer: hiding internal data and exposing it through members/properties.
- What is the difference between a class and an object? Answer: class is a blueprint; object is an instance of the class.
2. Type Safety
Plain-language definition and why it matters. Type safety means the compiler/runtime prevents operations on incompatible types (e.g., adding a string to an int without explicit conversion). It matters because it catches errors at compile time instead of runtime, making .NET programs more reliable.
Core theory. C# is statically and strongly typed: every variable has a declared type; assignments and operations are checked. Implicit conversions allowed only when safe (int → long); unsafe ones need casts (long → int) or parsing. var still has a fixed type inferred at compile time. Boxing/unboxing: converting value types to/from object (reference type) has a cost and can fail at unboxing if types mismatch.
Syntax / notation.
int x = 10;
// string s = x; // compile error (not type-safe)
int y = (int)(long)10L; // explicit cast
var z = 20; // inferred as int
object o = x; // boxing
int w = (int)o; // unboxing
Worked example. Parsing user input safely:
string input = "100";
if (int.TryParse(input, out int number)) { ... } // type-safe parse
else { ... }
Realistic use case. A banking app rejects assigning a string account number to a decimal balance field at compile time.
Comparison table.
| Safe | Unsafe (needs cast/parse) | |
|---|---|---|
| int → long | implicit | — |
| long → int | — | explicit cast |
| string → int | — | int.Parse/TryParse |
| int → object | boxing | — |
Common mistakes / limitations. InvalidCastException on bad unboxing; relying on var without realizing the type is fixed; excessive boxing in loops (performance).
Exam-ready answer points. Define type safety; contrast static/strong typing; explain implicit vs explicit conversion; explain boxing/unboxing.
Self-check questions with answers.
- Is
vardynamically typed? Answer: no —varis statically typed; the compiler infers the type. - What is boxing? Answer: converting a value type to
object(reference type).
3. Memory Management
Plain-language definition and why it matters. Memory management in .NET is mostly automatic: the CLR allocates objects on the managed heap and the Garbage Collector (GC) reclaims unreachable memory. It matters because developers must still understand roots, generations, and IDisposable to avoid leaks and performance problems.
Core theory. Managed heap with generations (0, 1, 2): new objects in gen 0, promoted when they survive. GC runs when gen 0 is full, compacts memory, updates references. Roots: static fields, stack variables, CPU registers. IDisposable/using releases unmanaged resources (file handles, DB connections) deterministically; finalizers (~Class()) are non-deterministic backup. Large Object Heap (LOH) for objects > 85 KB.
Syntax / notation.
using (var conn = new SqlConnection(...)) { ... } // disposes conn
class TempFile : IDisposable { public void Dispose() { ... } }
Worked example. Reading a file safely:
using (var reader = new StreamReader("log.txt"))
{
string line = reader.ReadLine(); // file closed automatically at end
}
Realistic use case. A server that opens DB connections must wrap them in using or the connection pool exhausts before the GC runs.
Comparison table.
| Stack | Heap | |
|---|---|---|
| Holds | value types, references | objects (reference types) |
| Lifetime | method scope | until GC collects |
| Management | automatic (LIFO) | GC generations |
Common mistakes / limitations. Forgetting using on IDisposable (resource leak); keeping static references to objects (prevents GC); calling GC.Collect() manually (usually harmful).
Exam-ready answer points. Explain managed heap and generations; explain GC roots; explain IDisposable/using; contrast stack vs heap.
Self-check questions with answers.
- What does the Garbage Collector do? Answer: reclaims memory of unreachable objects on the managed heap.
- When should you use
using? Answer: for objects implementing IDisposable (unmanaged resources like files, DB connections).
4. Platform Support
Plain-language definition and why it matters. Platform support describes where .NET code can run. It matters because choosing the right .NET implementation (Framework, Core, Mono) affects target OS, deployment, and available APIs.
Core theory. .NET Framework: Windows-only, the original (WPF, WinForms, ASP.NET Web Forms). .NET Core / .NET 5+: cross-platform (Windows, Linux, macOS), open source, ASP.NET Core, console. Mono: cross-platform (historically, Xamarin for mobile). .NET Standard: a formal specification of APIs that implementations must support, enabling code sharing (libraries target .NET Standard; apps target Framework/Core).
Syntax / notation. Conceptual; target framework monikers like net472, net6.0, netstandard2.0 in .csproj.
Worked example. A class library targets netstandard2.0 so both a .NET Framework desktop app and a .NET 6 web app can reference it.
Realistic use case. A company keeps a legacy WPF app on .NET Framework (Windows) and builds a new Linux web service on .NET 6, sharing a netstandard2.0 library.
Comparison table.
| Implementation | OS | Notes |
|---|---|---|
| .NET Framework | Windows | legacy, WPF/WinForms/Web Forms |
| .NET Core / .NET 5+ | Win/Linux/macOS | modern, cross-platform, open source |
| Mono | cross-platform | historically; Xamarin mobile |
| .NET Standard | spec (not runtime) | API contract for library sharing |
Common mistakes / limitations. Treating .NET Framework as cross-platform (it's Windows-only); assuming all .NET Standard APIs exist on every implementation.
Exam-ready answer points. List .NET implementations and OS support; explain .NET Framework vs .NET Core vs .NET Standard; state library-sharing purpose of .NET Standard.
Self-check questions with answers.
- Which .NET implementation is Windows-only? Answer: .NET Framework.
- What is .NET Standard? Answer: a formal API specification (contract) implementations support, used for sharing libraries.
5. C# and CLR
Plain-language definition and why it matters. C# is the language; the CLR (Common Language Runtime) is the runtime that executes C# code. They matter because C# compiles to Intermediate Language (IL), which the CLR JIT-compiles to native code and manages (memory, security, exceptions).
Core theory. C# source → compiler → IL (Microsoft Intermediate Language) stored in assemblies (.dll/.exe) with metadata. At runtime, CLR loads the assembly, JIT-compiles IL to native machine code, and executes. CLR services: garbage collection, type safety, exception handling, code access security (legacy), thread management. Just-In-Time (JIT) compiles methods on first call; Ahead-Of-Time (AOT) options exist (e.g., ReadyToRun).
Syntax / notation. Conceptual: source.cs → csc → IL in assembly → CLR JIT → native code.
Worked example. csc Program.cs produces Program.exe containing IL; running it triggers the CLR to JIT-compile and execute Main.
Realistic use case. A C# assembly compiled on Windows can run on any machine with a compatible CLR because IL is portable.
Comparison table.
| Step | Input | Output |
|---|---|---|
| Compile | C# source | IL + metadata (assembly) |
| JIT | IL at runtime | native machine code |
| Execute | native code | program behavior |
Common mistakes / limitations. Confusing C# (language) with .NET (platform/runtime); thinking C# compiles directly to machine code (it compiles to IL first).
Exam-ready answer points. Describe C# → IL → CLR → native flow; name CLR services (GC, type safety, exceptions); explain JIT.
Self-check questions with answers.
- What does C# compile to? Answer: Intermediate Language (IL) stored in an assembly.
- What is JIT compilation? Answer: compiling IL to native code at runtime, on first use.
6. CLR and .NET Framework
Plain-language definition and why it matters. The CLR is the runtime component of the .NET Framework; the .NET Framework is the broader platform (CLR + class libraries + languages). Understanding the relationship clarifies where C# fits.
Core theory. .NET Framework = CLR + .NET Framework Class Library (FCL: System, System.Collections, System.IO, System.Data, System.Web, etc.) + languages (C#, VB.NET, F#). The CLR provides the execution environment (IL, JIT, GC, type loader, security). Assemblies reference FCL types. Windows-only in the original .NET Framework.
Syntax / notation. Referencing: using System; then Console.WriteLine(...).
Worked example. A console app uses System.Console (FCL) and runs under the CLR on Windows.
Realistic use case. A legacy Windows desktop app runs entirely on the .NET Framework CLR and FCL.
Comparison table.
| CLR | .NET Framework | |
|---|---|---|
| Role | runtime execution | full platform (CLR + libraries) |
| Provides | GC, JIT, type safety, security | FCL, languages, tools |
| Scope | component | whole product |
Common mistakes / limitations. Saying "CLR and .NET Framework are the same" (CLR is part of .NET Framework); assuming .NET Framework runs on Linux.
Exam-ready answer points. Explain CLR vs .NET Framework; list FCL namespaces; state CLR services.
Self-check questions with answers.
- Is the CLR the whole .NET Framework? Answer: no — the CLR is the runtime component; .NET Framework includes the CLR plus the class library and languages.
- Name one FCL namespace. Answer: System (or System.IO, System.Collections).
7. Other Frameworks
Plain-language definition and why it matters. "Other frameworks" refers to frameworks in/around the .NET ecosystem beyond the core .NET Framework (e.g., WPF, WCF, ASP.NET, Entity Framework, Xamarin/Mono). It matters because enterprise apps choose specialized frameworks for UI, services, data, and mobile.
Core theory. WPF (desktop UI on Windows), WCF (service-oriented communication), ASP.NET (web), ASP.NET MVC/Web API, Entity Framework (ORM/database), Windows Workflow (WF), Xamarin/Mono (mobile, historically). Each targets a scenario; some are .NET Framework–specific (WPF/WCF) while ASP.NET Core and EF Core are cross-platform.
Syntax / notation. Conceptual; NuGet packages like Microsoft.EntityFrameworkCore.
Worked example. An enterprise app uses WPF for the desktop UI, WCF for backend services, and Entity Framework for database access — three frameworks in one solution.
Realistic use case. A Nepali bank uses Windows Forms/WPF for teller desktop apps and ASP.NET for the online banking portal.
Comparison table.
| Framework | Purpose | Platform |
|---|---|---|
| WPF | rich desktop UI | Windows (.NET Framework) |
| WCF | distributed services | Windows (.NET Framework) |
| ASP.NET | web applications | Windows (Framework) / cross-platform (Core) |
| Entity Framework | data access / ORM | both |
| Xamarin | mobile apps | iOS/Android (via Mono) |
Common mistakes / limitations. Assuming WCF/WPF run cross-platform (they don't); mixing Entity Framework (Framework) and EF Core (Core) APIs incorrectly.
Exam-ready answer points. List other .NET frameworks and their purposes; note platform limitations; give one enterprise combination.
Self-check questions with answers.
- Which framework builds rich Windows desktop UIs? Answer: WPF (Windows Presentation Foundation).
- Which framework is used for object-relational mapping? Answer: Entity Framework.
8. Framework Overview
Plain-language definition and why it matters. A framework overview maps the layers of .NET: languages at top, base class library in the middle, CLR at the bottom. It matters because it shows how a C# program relies on the stack below it.
Core theory. Layers: (1) Languages: C#, VB.NET, F#. (2) Base Class Library (BCL/FCL): System.* namespaces (collections, IO, threading, reflection). (3) CLR: execution, GC, JIT, security, type system. (4) OS/hardware at bottom. Additional layers: ASP.NET, ADO.NET, Windows Forms/WPF on top of the BCL. All languages compile to IL, so they interoperate in the same assembly.
Syntax / notation. Conceptual stack diagram: App → BCL → CLR → OS.
Worked example. Console.WriteLine("x"): C# (language) calls System.Console (BCL), executed by the CLR on the OS.
Realistic use case. A single solution contains a C# library and a VB.NET test project; both compile to IL and interoperate because they share the CLR/BCL.
Comparison table.
| Layer | Examples | Responsibility |
|---|---|---|
| Language | C#, VB.NET, F# | write code |
| BCL/FCL | System, Collections, IO | reusable types |
| CLR | GC, JIT, type loader | execute and manage |
| OS/Hardware | Windows/Linux | run the process |
Common mistakes / limitations. Thinking each language needs its own runtime (they share the CLR); skipping the BCL and calling OS APIs directly (loses portability).
Exam-ready answer points. Draw/describe the .NET stack; explain language interoperability via IL; name layers and responsibilities.
Self-check questions with answers.
- What is at the bottom of the .NET stack? Answer: the OS/hardware (above it, the CLR).
- Why can C# and VB.NET interoperate? Answer: both compile to IL executed by the same CLR.
9. .NET Standard 2.0
Plain-language definition and why it matters. .NET Standard 2.0 is a formal specification of APIs that .NET implementations must provide. It matters because libraries targeting .NET Standard 2.0 can be shared across .NET Framework, .NET Core, and Mono, solving code reuse.
Core theory. .NET Standard is not a runtime; it's an API contract (set of types/members). Implementations declare which versions they support (.NET Framework 4.6.1+ supports .NET Standard 2.0; .NET Core 2.0+ supports it). Version numbers: higher .NET Standard = more APIs but fewer implementations support it; lower = broader support. .NET Standard 2.0 added ~20,000 APIs (including many from .NET Framework) to ease migration.
Syntax / notation. Target in .csproj: <TargetFramework>netstandard2.0</TargetFramework>.
Worked example. A library targets netstandard2.0; it is referenced by both an old .NET Framework 4.7.2 app and a new .NET 6 app without recompiling the library.
Realistic use case. A shared NuGet library (e.g., validation logic) targets netstandard2.0 so all company apps, regardless of runtime, can use it.
Comparison table.
| .NET Standard | .NET Framework / .NET Core | |
|---|---|---|
| What | API specification (contract) | runtime + implementation |
| Can run alone? | no | yes |
| Purpose | library code sharing | building/running apps |
Common mistakes / limitations. Treating .NET Standard as installable (it's a spec); targeting too high a version and excluding older apps.
Exam-ready answer points. Define .NET Standard 2.0; explain it's a spec not runtime; explain library sharing across implementations; mention version trade-off.
Self-check questions with answers.
- Is .NET Standard a runtime? Answer: no — it's an API specification/contract.
- Why target .NET Standard 2.0? Answer: so a library can be shared across .NET Framework and .NET Core/Mono.
10. Applied Technologies
Plain-language definition and why it matters. Applied technologies are the real-world .NET tools used to build applications: ASP.NET (web), ADO.NET (data), WPF/WinForms (desktop), WCF (services), LINQ (query), Entity Framework (ORM). It matters because these are what developers actually use to deliver software.
Core theory. ASP.NET: server-side web (Web Forms, MVC, Web API). ADO.NET: direct data access (SqlConnection, Command, DataReader). LINQ: query collections/databases in C# syntax. WPF/WinForms: desktop UI. WCF: SOAP services. Entity Framework: ORM (maps tables to classes). NuGet: package manager for libraries.
Syntax / notation. LINQ example: from p in products where p.Price > 100 select p.
Worked example. A report tool: ADO.NET reads rows, LINQ filters them in memory, WPF displays in a grid.
Realistic use case. An inventory system: ASP.NET Core web front-end + Entity Framework data layer + SQL Server.
Comparison table.
| Technology | Purpose |
|---|---|
| ASP.NET | web applications |
| ADO.NET | direct database access |
| LINQ | in-memory/database queries |
| WPF/WinForms | desktop UI |
| WCF | SOAP web services |
| Entity Framework | ORM |
Common mistakes / limitations. Confusing ADO.NET (direct, manual) with Entity Framework (ORM, higher-level); using Web Forms for new greenfield (ASP.NET Core MVC is modern).
Exam-ready answer points. List applied technologies with purposes; contrast ADO.NET vs Entity Framework; mention NuGet.
Self-check questions with answers.
- Which technology maps database tables to C# classes? Answer: Entity Framework (ORM).
- What is NuGet? Answer: the .NET package manager for libraries.
Key terms — Unit 1
object orientation · encapsulation · inheritance · polymorphism · abstraction · class · object · type safety · static · strong · implicit/explicit conversion · boxing · unboxing · var · memory management · Garbage Collector · generations · roots · IDisposable · using · stack · heap · platform support · .NET Framework · .NET Core · .NET 5+ · Mono · .NET Standard · CLR · IL · JIT · assembly · metadata · FCL/BCL · C# · VB.NET · F# · WPF · WCF · ASP.NET · Entity Framework · NuGet · .NET Standard 2.0
Unit summary — Unit 1
C# is object-oriented with encapsulation/inheritance/polymorphism/abstraction; it is statically and strongly typed with boxing/unboxing. Memory is managed by the CLR Garbage Collector (generations, roots) plus IDisposable/using for deterministic cleanup. .NET has multiple implementations: .NET Framework (Windows), .NET Core/.NET 5+ (cross-platform), Mono, and the .NET Standard API contract for library sharing. C# compiles to IL executed by the CLR (JIT). Applied technologies include ASP.NET, ADO.NET, LINQ, WPF/WinForms, WCF, and Entity Framework.
Unit 2: The C# Language Basics
Teaching hours: 12
Topics in outline order
- Writing Console and GUI Applications
- Identifiers and Keywords
- Writing Comments
- Data Types
- Expressions and Operators
- Strings and Characters
- Arrays
- Variables and Parameters
- Statements (Declaration, Expression, Selection, Iteration, and Jump Statements)
- Namespaces
1. Writing Console and GUI Applications
Plain-language definition and why it matters. Console applications run in a terminal (text input/output); GUI applications use windows and controls (WPF, Windows Forms, or modern MAUI/WinUI). This matters because it's the first hands-on experience: console for learning/logic, GUI for user-facing programs.
Core theory. Console: System.Console (Write, WriteLine, ReadLine), Main entry point (static void Main(string[] args) or static Task<int> Main). GUI: a window/Application with controls (Button, TextBox, Label) and event handlers (e.g., button Click). WPF uses XAML for markup + C# code-behind; Windows Forms uses designer + code.
Syntax / notation. Console:
static void Main(string[] args)
{
System.Console.Write("Enter name: ");
string name = System.Console.ReadLine();
System.Console.WriteLine($"Hello, {name}");
}
Worked example. Console greeting program: prompts for name, reads it, prints personalized message. Compile with csc or dotnet run; run from terminal.
Realistic use case. A small utility (e.g., batch file renamer) is a console app; a desktop data-entry tool is a GUI app.
Comparison table.
| Console | GUI | |
|---|---|---|
| Interface | text terminal | windows, controls |
| Input | Console.ReadLine | text boxes, buttons |
| Output | Console.WriteLine | labels, grids |
| Use case | utilities, learning | user-facing apps |
Common mistakes / limitations. Forgetting static void Main signature (no entry point); blocking the GUI thread with long work (freeze the window) — use background threads/async.
Exam-ready answer points. Describe console vs GUI; show Main signature and Console methods; name GUI controls/event handlers.
Self-check questions with answers.
- What is the entry point of a C# console app? Answer:
Main(e.g.,static void Main(string[] args)). - Name one GUI input control. Answer: TextBox (or Button, Label).
2. Identifiers and Keywords
Plain-language definition and why it matters. Identifiers are programmer-chosen names (classes, methods, variables); keywords are reserved words with special meaning (class, if, while, return). Rules matter because invalid names won't compile and keywords can't be used as identifiers unless prefixed with @.
Core theory. Identifier rules: start with letter or underscore; continue with letters, digits, underscore; case-sensitive; no keywords unless @if (verbatim identifier). Naming conventions: PascalCase for types/methods (Customer, GetName), camelCase for locals/parameters (customer, getName). Contextual keywords (e.g., var, yield, where) have meaning in specific contexts.
Syntax / notation.
int myVariable = 5; // camelCase local
public class Customer { } // PascalCase type
string @class = "math"; // @ escapes keyword 'class'
Worked example. Valid identifiers: customerName, _count, Item1. Invalid: 123abc (starts with digit), class (keyword) unless @class.
Realistic use case. A team follows conventions so Order (class) and order (parameter) are clearly different.
Comparison table.
| Example | Rule | |
|---|---|---|
| Valid identifier | totalAmount, _id |
letter/_ start, case-sensitive |
| Keyword | class, if, return |
reserved (use @ to override) |
| Contextual keyword | var, yield |
context-dependent |
Common mistakes / limitations. Starting identifiers with digits; using keywords raw (int class = 5;); inconsistent casing confusing team members.
Exam-ready answer points. State identifier rules; distinguish keywords vs identifiers; show @ verbatim; name casing conventions.
Self-check questions with answers.
- Can
classbe used as an identifier? Answer: only with@prefix:@class. - Is C# case-sensitive for identifiers? Answer: yes —
Totalandtotaldiffer.
3. Writing Comments
Plain-language definition and why it matters. Comments are ignored by the compiler and document code for humans. They matter for maintainability: explaining why, not just what.
Core theory. Single-line: // comment. Multi-line: /* ... */. XML documentation: /// for types/members (generates IntelliSense and XML docs files), using <summary>, <param>, <returns>, <seealso>. Good comments explain intent; bad comments restate obvious code.
Syntax / notation.
// single line
/* multi
line */
/// <summary>Calculates the total.</summary>
/// <param name="items">price list</param>
/// <returns>sum</returns>
public decimal Total(List<decimal> items) { ... }
Worked example. Documenting a method:
/// <summary>Applies a discount percentage to a price.</summary>
/// <param name="price">original price</param>
/// <param name="discount">discount in percent (0-100)</param>
public decimal ApplyDiscount(decimal price, decimal discount) { ... }
Realistic use case. XML /// comments on a class library let other developers see parameter descriptions in IntelliSense.
Comparison table.
| Type | Syntax | Use |
|---|---|---|
| Single-line | // |
brief notes |
| Multi-line | /* */ |
block comments |
| XML doc | /// |
API documentation/IntelliSense |
Common mistakes / limitations. Commenting out large blocks left in code; outdated comments that mislead; commenting obvious code (i++ // increment i).
Exam-ready answer points. List comment styles; explain XML documentation tags; state good comment practice (explain why).
Self-check questions with answers.
- Which comment style is used for API documentation? Answer: XML doc comments (
///). - Are comments executed? Answer: no — the compiler ignores them.
4. Data Types
Plain-language definition and why it matters. Data types define what kind of data a variable holds and what operations are allowed. C# has value types (structs, enums) and reference types (classes, strings, arrays, delegates). Choosing the right type affects correctness, memory, and performance.
Core theory. Value types: int, double, decimal, bool, char, struct, enum — stored on stack (or inline), copied on assignment. Reference types: class, string, array, delegate, interface — stored on heap, variable holds a reference. decimal for money (precision), double for scientific, string is immutable reference type, DateTime for dates. Nullable value types int? allow null.
Syntax / notation.
int count = 5; // value type
decimal price = 19.99m; // money suffix m
string name = "Sita"; // reference type (immutable)
int? nullable = null; // nullable value type
Worked example. Money calculation: use decimal not double to avoid rounding errors: decimal total = 10.05m + 2.10m; // 12.15m.
Realistic use case. A financial ledger uses decimal for amounts to preserve exact cents.
Comparison table.
| Category | Examples | Storage | Assignment |
|---|---|---|---|
| Value | int, double, decimal, bool, char, struct, enum | stack/inline | copied |
| Reference | class, string, array, delegate, interface | heap | reference copied |
| Nullable | int?, double? | value + null flag | can be null |
Swipe to see all columns
Common mistakes / limitations. Using double for money (rounding); assuming strings are value types (they're reference but immutable — == compares content); null reference exceptions.
Exam-ready answer points. List value vs reference types; give examples; explain decimal for money; explain int?.
Self-check questions with answers.
- Is
stringa value or reference type? Answer: reference type (though immutable and==compares content). - Which type should represent money? Answer:
decimal.
5. Expressions and Operators
Plain-language definition and why it matters. Expressions combine values, variables, and operators to produce a result. Operators are symbols (+, -, *, /, %, ==, &&, =). Understanding precedence and overloadability matters for correct calculations and logic.
Core theory. Arithmetic: + - * / %. Relational: == != < > <= >=. Logical: && || !. Assignment: = += -=. Increment/decrement: ++ -- (prefix vs postfix). Ternary conditional: condition ? a : b. Operator precedence: ()* /% +- relational && || ?: =. Some operators can be overloaded for custom types.
Syntax / notation.
int a = 10, b = 3;
int sum = a + b; // 13
int rem = a % b; // 1
bool big = a > 5 && b < 5; // true && false = false
string result = a > b ? "a" : "b"; // "a"
Worked example. Calculate average:
double average = (x + y + z) / 3.0; // parentheses ensure sum first; 3.0 forces double division
Realistic use case. An e-commerce discount: finalPrice = price > 1000 ? price * 0.9m : price; (ternary).
Comparison table.
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / % | 10 % 3 = 1 |
| Relational | == != < > <= >= | 5 == 5 |
| Logical | && | |
| Assignment | = += -= | x += 1 |
| Conditional | ? : | x > 0 ? "pos" : "neg" |
Common mistakes / limitations. Integer division truncates (5/2 = 2); use 5.0/2. Confusing = (assignment) with == (equality). Postfix x++ returns old value.
Exam-ready answer points. List operator categories with examples; explain precedence; show ternary; warn on integer division and = vs ==.
Self-check questions with answers.
- What is
10 % 3? Answer: 1 (remainder). - Difference between
=and==? Answer:=assigns;==compares equality.
6. Strings and Characters
Plain-language definition and why it matters. Strings (System.String) are immutable sequences of characters; char is a single UTF-16 character. Strings are used everywhere (input, messages, data). Immutability means every "modification" creates a new string, which matters for performance in loops (use StringBuilder).
Core theory. String literals with ""; verbatim strings @"C:\path" (no escape processing); interpolated strings $"Hello {name}"; escape sequences (\n, \t, \\, \"). string is a keyword alias for System.String. Common members: Length, Trim(), ToUpper(), ToLower(), Substring(), IndexOf(), Replace(), Split(). StringBuilder for efficient repeated modification.
Syntax / notation.
string name = "Sita";
string path = @"C:\Users\docs"; // verbatim
string msg = $"Hello, {name}"; // interpolation
var sb = new System.Text.StringBuilder();
sb.Append("a").Append("b");
string result = sb.ToString();
Worked example. Build a file path and a message:
string folder = @"C:\data";
string file = $"report_{DateTime.Today:yyyyMMdd}.txt";
string fullPath = System.IO.Path.Combine(folder, file);
Realistic use case. Generating personalized emails with interpolated strings and assembling CSV lines with StringBuilder for speed.
Comparison table.
string |
StringBuilder |
|
|---|---|---|
| Mutability | immutable (new object per change) | mutable |
| Best for | fixed/few changes | loops, many appends |
| Example | "hello" |
Append in a loop |
Common mistakes / limitations. Assuming s.ToUpper() changes s (it returns a new string; must reassign); string concatenation in a loop creates many objects (use StringBuilder).
Exam-ready answer points. Explain string immutability; show verbatim and interpolated strings; list common string methods; explain when to use StringBuilder.
Self-check questions with answers.
- Are strings mutable in C#? Answer: no — strings are immutable; each change creates a new string.
- Which class should you use to build a string in a loop? Answer:
System.Text.StringBuilder.
7. Arrays
Plain-language definition and why it matters. Arrays are fixed-size, ordered collections of same-type elements. They matter because they are the simplest collection and the basis for many other collections.
Core theory. Declaration and instantiation: int[] numbers = new int[5]; or int[] numbers = {1,2,3};. Zero-based indexing (numbers[0]). Length property. Arrays are reference types (the variable holds a reference; elements can be value or reference types). Multi-dimensional: int[,] matrix = new int[3,3];; jagged: int[][] jagged = new int[2][];. foreach for read-only iteration; for with index for modification.
Syntax / notation.
int[] scores = { 85, 90, 78 };
int first = scores[0]; // 85
scores[1] = 95; // modify
foreach (int s in scores) { ... }
Worked example. Find max:
int max = scores[0];
for (int i = 1; i < scores.Length; i++)
if (scores[i] > max) max = scores[i];
Realistic use case. Storing a fixed set of daily temperatures for a week.
Comparison table.
| Single-dim | Multi-dim ([,]) |
Jagged ([][]) |
|
|---|---|---|---|
| Shape | row | rectangular | array of arrays |
| Declaration | int[5] |
int[3,3] |
int[2][] |
Swipe to see all columns
Common mistakes / limitations. Index out of range (scores[5] on length 5); arrays are fixed size (use List<T> for resizable); arrays are covariant in a way that can cause runtime type errors.
Exam-ready answer points. Show array declaration/indexing; explain Length and zero-based indexing; contrast single/multi/jagged; mention foreach vs for.
Self-check questions with answers.
- What is the index of the first array element? Answer: 0 (zero-based).
- Are arrays resizable after creation? Answer: no — fixed size; use
List<T>to resize.
8. Variables and Parameters
Plain-language definition and why it matters. Variables store data; parameters pass data into methods. Understanding scope, lifetime, and parameter passing (by value vs by reference) matters for correct data flow.
Core theory. Variable scope: block, method, class. Fields (class-level) vs locals (method-level). Parameter passing: by value (default — copy; changes don't affect caller), ref (reference, must be initialized), out (output, assigned inside method), params (variable number of arguments). Optional parameters and named arguments. const (compile-time constant) vs readonly (runtime constant, set in constructor).
Syntax / notation.
void Increment(ref int x) { x++; } // ref
void Get(out int x) { x = 10; } // out
void Print(params string[] names) { ... } // params
const int Max = 100; // compile-time
readonly int Id = 5; // runtime
Worked example. Swap using ref:
int a = 1, b = 2;
Swap(ref a, ref b); // a=2, b=1
void Swap(ref int x, ref int y) { int t = x; x = y; y = t; }
Realistic use case. A TryParse pattern uses out to return success and a value together.
Comparison table.
| ref | out | params | |
|---|---|---|---|
| Initialization before call | required | not required | — |
| Direction | in/out | out only | variable args |
Swipe to see all columns
Common mistakes / limitations. Using ref when a simple return suffices; forgetting to assign out parameters (compile error); const cannot change, readonly can be set once in constructor.
Exam-ready answer points. Explain value vs ref/out/params; const vs readonly; scope examples.
Self-check questions with answers.
- Difference between
refandout? Answer:refrequires initialization before the call;outmust be assigned inside the method. - What does
constmean? Answer: compile-time constant (cannot change).
9. Statements (Declaration, Expression, Selection, Iteration, and Jump Statements)
Plain-language definition and why it matters. Statements are the executable units of C#. Declaration statements create variables; expression statements do work; selection (if, switch) chooses; iteration (while, for, foreach, do) repeats; jump (break, continue, return, goto) transfers control. Mastery is required to write any program logic.
Core theory. Declaration: int x = 5;. Expression: x = x + 1;, method call ;. Selection: if/else, switch (with pattern matching in modern C#). Iteration: while, do...while, for, foreach. Jump: break (exit loop/switch), continue (next iteration), return (exit method with value), goto (rare). Scope of variables declared in for/foreach is the loop.
Syntax / notation.
if (score >= 60) Console.WriteLine("Pass"); else Console.WriteLine("Fail");
switch (grade) { case 'A': ...; break; default: ...; break; }
for (int i = 0; i < 5; i++) { ... }
foreach (var item in list) { ... }
while (condition) { ... }
Worked example. Print pass/fail and sum 1..5:
int sum = 0;
for (int i = 1; i <= 5; i++) sum += i; // sum = 15
string status = score >= 60 ? "Pass" : "Fail";
Realistic use case. A grading program iterates over student scores and uses selection to assign grades.
Comparison table.
| Statement kind | Examples | Purpose |
|---|---|---|
| Declaration | int x = 5; |
declare variable |
| Expression | x++;, M(); |
perform action |
| Selection | if, switch |
choose branch |
| Iteration | for, while, foreach |
repeat |
| Jump | break, continue, return |
transfer control |
Common mistakes / limitations. Forgetting break in switch (fall-through in C# only allowed if case is empty); infinite loops (missing increment/modification); modifying a collection while foreach iterating (invalid operation).
Exam-ready answer points. Categorize statements; show if, switch, for, foreach, while; explain break/continue/return.
Self-check questions with answers.
- Which loop is best for iterating a collection read-only? Answer:
foreach. - What does
continuedo? Answer: skips to the next iteration of the loop.
10. Namespaces
Plain-language definition and why it matters. Namespaces organize types into hierarchical groups and prevent name collisions (e.g., two classes both named List). They matter because the .NET Framework has thousands of types; namespaces keep them manageable.
Core theory. Declaration: namespace Company.Project { class C {} }. Referenced with using Company.Project; so types can be used unqualified, or fully qualified Company.Project.C. Nesting namespaces. The global:: qualifier for the root. System is the root namespace; using System; brings Console, String, etc.
Syntax / notation.
namespace Acme.Payroll
{
public class Employee { }
}
// usage
using Acme.Payroll;
var e = new Employee();
// or fully qualified
var e2 = new Acme.Payroll.Employee();
Worked example. Two libraries both define Configuration; namespaces App.Config and Db.Config prevent collision; the code picks one with using or qualification.
Realistic use case. A large solution organizes Company.UI, Company.Data, Company.Services namespaces.
Comparison table.
using |
fully qualified | |
|---|---|---|
| Typing | less (unqualified names) | more (A.B.C) |
| Collision handling | may need alias (using C = A.B.C;) |
never ambiguous |
Common mistakes / limitations. Forgetting using System; (then Console unresolved); name collisions resolved only by full qualification or aliases; circular namespace references not an issue (namespaces aren't circular dependencies).
Exam-ready answer points. Explain namespace purpose; show using and qualification; explain collision prevention; name System as root.
Self-check questions with answers.
- What is the purpose of a namespace? Answer: organize types and prevent name collisions.
- What is the root namespace in .NET? Answer:
System.
Key terms — Unit 2
console · GUI · Main · entry point · identifier · keyword · @ verbatim · comment · XML doc /// · data type · value type · reference type · decimal · int? · expression · operator · precedence · ternary · string · immutable · StringBuilder · array · zero-based · Length · multi-dim · jagged · variable · parameter · ref · out · params · const · readonly · statement · if · switch · for · foreach · while · break · continue · return · namespace · using · fully qualified
Unit summary — Unit 2
Console apps use Main and System.Console; GUI apps use windows/controls/event handlers. Identifiers follow casing rules; keywords are reserved (use @ to escape). Comments (//, /* */, /// XML) document code. Data types split into value (int, decimal, struct) and reference (class, string, array); decimal for money; int? nullable. Operators (+, -, *, /, %, ==, &&, ?: ) with precedence; strings are immutable (use StringBuilder in loops). Arrays are fixed, zero-based, with Length. Parameters pass by value/ref/out/params; const vs readonly. Statements: declaration/expression/selection/iteration/jump. Namespaces organize types and avoid collisions via using/qualification.
Unit 3: Creating Types in C#
Teaching hours: 12
Topics in outline order
- Classes
- Constructors and Deconstructors
- this Reference
- Properties
- Indexers
- Static Constructors and Classes
- Finalizers
- Dynamic Binding
- Operator Overloading
- Inheritance
- Abstract Classes and Methods
- base Keyword
- Overloading
- Object Type
- Structs
- Access Modifiers
- Interfaces
- Enums
- Generics
1. Classes
Plain-language definition and why it matters. A class is a user-defined type that defines fields, properties, methods, events, and constructors. Classes are the primary building blocks of C# programs and realize object orientation.
Core theory. Declaration: class Name { members }. Members: fields (data), properties (accessors), methods (behavior), constructors (initialization), events. Access modifiers (public/private/protected/internal) control visibility. object is the ultimate base class. Partial classes split a class across files.
Syntax / notation.
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public decimal Total(decimal qty) => Price * qty;
}
var p = new Product { Name = "Book", Price = 120m };
Worked example. Product class with auto-properties and a method; instantiation with object initializer.
Realistic use case. An inventory system models Product, Order, Customer as classes.
Comparison table.
| Member | Purpose |
|---|---|
| Field | stores data |
| Property | controlled access to data |
| Method | behavior |
| Constructor | initializes object |
| Event | notifications |
Common mistakes / limitations. Public fields (break encapsulation; use properties); forgetting new (null reference).
Exam-ready answer points. Define class and members; show instantiation; explain access modifiers.
Self-check questions with answers.
- What is a class? Answer: a user-defined type blueprint with fields, properties, methods, constructors.
- How do you create an object? Answer:
new ClassName().
2. Constructors and Deconstructors
Plain-language definition and why it matters. Constructors initialize objects when created; deconstructors (C# 7 deconstruction) split an object into variables. Constructors matter because objects must start in a valid state.
Core theory. Constructors: same name as class, no return type, can be overloaded; default constructor provided if none written; static constructor initializes static members once. Deconstruction: var (x, y) = point; requires a Deconstruct method. this constructor chaining calls another constructor in same class.
Syntax / notation.
public class Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y) { X = x; Y = y; }
public void Deconstruct(out int x, out int y) { x = X; y = Y; }
}
// usage
var p = new Point(3, 4);
var (x, y) = p; // x=3, y=4
Worked example. Point class with constructor and deconstruction.
Realistic use case. Deconstructing a Customer into name and email variables for a tuple-like use.
Comparison table.
| Constructor | Deconstructor | |
|---|---|---|
| Purpose | initialize object | split object into variables |
| Syntax | ClassName(...) |
Deconstruct(out ...) |
| Invocation | new |
var (a,b) = obj; |
Common mistakes / limitations. Deconstruction requires writing Deconstruct; structs support it too; not to be confused with finalizers (~Class()).
Exam-ready answer points. Explain constructor overloading/chaining; show deconstruction syntax.
Self-check questions with answers.
- Can constructors be overloaded? Answer: yes (different parameter lists).
- What does deconstruction do? Answer: splits an object's members into separate variables (
var (a,b) = obj).
3. this Reference
Plain-language definition and why it matters. this refers to the current instance of the class. It matters to disambiguate instance members from parameters/local variables with the same name and to pass the current object to other methods.
Core theory. this.field vs parameter. Used in constructors/properties/setters when parameter shadows a field. this() calls another constructor. this cannot be used in static members (no instance).
Syntax / notation.
public class Account
{
private decimal balance;
public Account(decimal balance) { this.balance = balance; } // field vs param
}
Worked example. Constructor parameter balance shadows field balance; this.balance = balance; assigns field from parameter.
Realistic use case. Setter methods where the argument name matches the property name.
Comparison table.
this.balance |
balance (param) |
|
|---|---|---|
| Refers to | instance field | local parameter |
Common mistakes / limitations. Using this in static methods (compile error); assuming this is required (only needed when names collide).
Exam-ready answer points. Explain this disambiguation and constructor chaining; note static-member restriction.
Self-check questions with answers.
- When must you use
this? Answer: when a parameter/local shadows an instance field. - Can
thisbe used in a static method? Answer: no — static members have no instance.
4. Properties
Plain-language definition and why it matters. Properties provide controlled access to a class's data (get/set) while encapsulating backing fields. They matter because they let you validate, compute, or lazy-load while keeping field syntax.
Core theory. Property with getter/setter: public int Age { get; set; } (auto-property) or with backing field and logic. Read-only (get only), write-only (set only), computed properties. Property syntax looks like a field but executes code.
Syntax / notation.
public class Product
{
private decimal _price;
public decimal Price
{
get => _price;
set { if (value < 0) throw ...; _price = value; }
}
}
Worked example. Price property rejects negative values via setter validation.
Realistic use case. A Person.Age property computes age from birthdate instead of storing it.
Comparison table.
| Field | Property | |
|---|---|---|
| Access | direct | via get/set (can validate/log) |
| Encapsulation | weak | strong |
| Syntax | obj.x |
obj.x (same, but code runs) |
Common mistakes / limitations. Auto-properties with no backing logic still fine; forgetting get/set makes read-only/write-only; infinite recursion if property accesses itself (use backing field).
Exam-ready answer points. Explain property get/set, backing field, validation, read-only/write-only.
Self-check questions with answers.
- Why use a property instead of a public field? Answer: encapsulation — validate/transform on get/set.
- What is an auto-property? Answer:
{ get; set; }with compiler-generated backing field.
5. Indexers
Plain-language definition and why it matters. Indexers let instances be indexed like arrays (obj[i]). They matter for collection-like classes (e.g., a custom list or matrix) where element access by index is natural.
Core theory. Indexer declared with this keyword and parameters: public Type this[int i] { get {...} set {...} }. Can be overloaded with different parameter types (int, string). Must have at least one get or set.
Syntax / notation.
public class Week
{
string[] days = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" };
public string this[int i] => days[i];
}
// usage
var w = new Week();
string day = w[0]; // "Sun"
Worked example. Week indexer returns day name by index.
Realistic use case. A Settings class indexed by string key: settings["theme"].
Comparison table.
| Method | Indexer | |
|---|---|---|
| Call | obj.Get(i) |
obj[i] |
| Keyword | name | this |
Common mistakes / limitations. Indexer must use this; cannot be static; read-only indexer allows only get.
Exam-ready answer points. Define indexer; show this[int] syntax; contrast with methods.
Self-check questions with answers.
- Which keyword declares an indexer? Answer:
this. - Can indexers be overloaded? Answer: yes, with different parameter types.
6. Static Constructors and Classes
Plain-language definition and why it matters. Static constructors initialize static state once before first use; static classes cannot be instantiated and contain only static members. They matter for shared, stateless utility data.
Core theory. Static constructor: static ClassName() — no access modifier, no parameters, runs automatically once (before first static member access or instance creation), initializes static fields. Static class: static class Name — cannot be instantiated, cannot have instance members, used for extension methods and utility (e.g., System.Math). readonly static fields set in static constructor.
Syntax / notation.
public static class Utils
{
static Utils() { /* init once */ }
public static int Add(int a, int b) => a + b;
}
// usage: Utils.Add(2,3); // cannot do new Utils()
Worked example. Utility class Math-like with static Add; static constructor logs initialization once.
Realistic use case. Conversion utilities (temperature, currency) as a static class with stateless methods.
Comparison table.
| Static class | Regular class | |
|---|---|---|
| Instantiation | not allowed (new forbidden) |
allowed |
| Members | static only | instance + static |
| Example | System.Math | Account |
Common mistakes / limitations. Trying new Utils() (compile error); adding instance members to static class; static constructor runs once, timing non-deterministic (before first use).
Exam-ready answer points. Explain static constructor (runs once, no params/modifier) and static class (no instantiation, static members only).
Self-check questions with answers.
- Can a static class be instantiated? Answer: no —
new StaticClass()is a compile error. - When does a static constructor run? Answer: once, before first access to any static member or instance creation.
7. Finalizers
Plain-language definition and why it matters. A finalizer (~ClassName()) is called by the GC before reclaiming an object, as a safety net for unmanaged resources. It matters because it's non-deterministic and should be paired with IDisposable (dispose pattern), not relied upon.
Core theory. Finalizer syntax ~ClassName() { ... }; cannot be called directly; runs on a finalizer thread at GC time; objects with finalizers take at least two GC cycles (finalization queue). Suppress finalization with GC.SuppressFinalize(this) in Dispose. Prefer SafeHandle/IDisposable over raw finalizers.
Syntax / notation.
class TempFile : IDisposable
{
~TempFile() { Dispose(false); } // finalizer
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
protected virtual void Dispose(bool disposing) { ... }
}
Worked example. A wrapper around a file handle releases it in Dispose (deterministic) and finalizer (backup).
Realistic use case. A class wrapping an OS file handle must ensure the handle closes even if the user forgets Dispose.
Comparison table.
| Dispose | Finalizer | |
|---|---|---|
| When | deterministic (user calls using) |
non-deterministic (GC) |
| Reliability | high | low (backup only) |
Common mistakes / limitations. Implementing a finalizer when SafeHandle/IDisposable suffices; doing heavy work in a finalizer (slows GC); resurrecting objects (avoid).
Exam-ready answer points. Explain finalizer purpose and non-determinism; explain dispose pattern with SuppressFinalize.
Self-check questions with answers.
- When does a finalizer run? Answer: non-deterministically, when the GC collects the object.
- Is a finalizer a replacement for
IDisposable? Answer: no — it's a backup; preferIDisposable/using.
8. Dynamic Binding
Plain-language definition and why it matters. Dynamic binding (dynamic type) defers type checking to runtime instead of compile time. It matters for interop with COM, dynamic languages, or loosely structured data, but loses compile-time safety and IntelliSense.
Core theory. dynamic x = ...; — compiler doesn't check member existence; errors surface at runtime (RuntimeBinderException). Use sparingly. var is compile-time (safe); dynamic is runtime (flexible). Dynamic objects implement IDynamicMetaObjectProvider (e.g., ExpandoObject).
Syntax / notation.
dynamic obj = GetObject();
obj.AnyMethod(); // checked at runtime
var safe = "text"; // compile-time type string
Worked example. Calling a method only known at runtime:
dynamic calc = GetCalculator();
int result = calc.Add(2, 3); // resolves Add at runtime
Realistic use case. Consuming a JSON response or COM object where members aren't known at compile time.
Comparison table.
| var | dynamic | |
|---|---|---|
| Type checked | compile time | runtime |
| Safety | high | lower (runtime errors) |
| IntelliSense | yes | no |
Common mistakes / limitations. Using dynamic for normal code (lose compile-time safety); RuntimeBinderException if member missing; performance cost of dynamic dispatch.
Exam-ready answer points. Define dynamic; contrast with var; name risks (RuntimeBinderException, performance).
Self-check questions with answers.
- Difference between
varanddynamic? Answer:varis compile-time typed;dynamicchecks members at runtime. - What error occurs if a
dynamicmember is missing? Answer: RuntimeBinderException at runtime.
9. Operator Overloading
Plain-language definition and why it matters. Operator overloading lets built-in operators (+, -, ==, <, etc.) work with custom types. It matters for natural syntax (e.g., money1 + money2) but should be used judiciously to avoid confusion.
Core theory. Declared as public static methods with operator keyword: public static Money operator +(Money a, Money b). At least one parameter must be the containing type. Overload related operators together (e.g., == and !=, < and >). Overloading == requires overriding Equals and GetHashCode.
Syntax / notation.
public class Money
{
public decimal Amount { get; }
public static Money operator +(Money a, Money b) => new Money(a.Amount + b.Amount);
}
var total = m1 + m2; // uses operator+
Worked example. Money addition via operator overloading.
Realistic use case. A Complex number type overloads +, -, * for math-like syntax.
Comparison table.
| Operator pair | Overload together |
|---|---|
| == | != |
| < | > |
| <= | >= |
Common mistakes / limitations. Overloading == without Equals/GetHashCode (inconsistent hashing); making operators do surprising things (violates least astonishment); not overloading both comparison directions.
Exam-ready answer points. Explain operator static method rule; related operator pairs; == requires Equals/GetHashCode.
Self-check questions with answers.
- Which keyword declares an operator overload? Answer:
operator(in a public static method). - If you overload
==, what else should you override? Answer:!=,Equals, andGetHashCode.
10. Inheritance
Plain-language definition and why it matters. Inheritance lets a derived class reuse and extend a base class. It matters for code reuse and polymorphism ("is-a" relationships).
Core theory. class Derived : Base. Single inheritance (one base class); all classes implicitly inherit from object. Derived adds/overrides members; virtual/override for polymorphism; sealed prevents further derivation; abstract classes can't be instantiated. Constructors: base constructor called implicitly or via base(...).
Syntax / notation.
public class Animal { public virtual void Speak() => Console.WriteLine("sound"); }
public class Dog : Animal { public override void Speak() => Console.WriteLine("bark"); }
Animal a = new Dog(); a.Speak(); // bark (polymorphism)
Worked example. Animal/Dog polymorphism via virtual/override.
Realistic use case. HR system: Employee base, FullTimeEmployee and PartTimeEmployee derived with different CalculatePay().
Comparison table.
| Inheritance | Composition | |
|---|---|---|
| Relationship | is-a | has-a |
| Coupling | tighter | looser |
| C# | single class inheritance | multiple interfaces possible |
Common mistakes / limitations. Deep inheritance (fragile base class); using inheritance when composition fits; forgetting virtual (can't override).
Exam-ready answer points. Explain : inheritance, virtual/override, sealed, abstract, base constructor call, single inheritance, object root.
Self-check questions with answers.
- Does C# support multiple class inheritance? Answer: no — single class inheritance (multiple interfaces allowed).
- What keyword lets a derived class replace a base method? Answer:
override(base method must bevirtual/abstract).
11. Abstract Classes and Methods
Plain-language definition and why it matters. Abstract classes/methods define a contract without full implementation. They matter for base types that shouldn't be instantiated and for forcing derived classes to implement specific behavior.
Core theory. abstract class cannot be instantiated; may contain abstract (no body) and non-abstract members. abstract method has no implementation; derived non-abstract class must override it. A class with any abstract members must be abstract. sealed prevents derivation; abstract and sealed are mutually exclusive on a class.
Syntax / notation.
public abstract class Shape
{
public abstract double Area(); // no body
public void Draw() => Console.WriteLine("drawing"); // concrete
}
public class Circle : Shape
{
public override double Area() => Math.PI * Radius * Radius;
}
// Shape s = new Shape(); // error
Worked example. Shape abstract class with Area(); Circle and Rectangle implement Area().
Realistic use case. A drawing app treats all shapes polymorphically via Shape.Area() without knowing concrete type.
Comparison table.
| Abstract class | Interface | |
|---|---|---|
| Can have state | yes (fields) | no (C# 8+ default members, but no instance state) |
| Instantiation | no | no |
| Inheritance | one base | multiple |
Common mistakes / limitations. Instantiating abstract class (compile error); forgetting to implement all abstract members (derived must be abstract too); mixing abstract and sealed on a class.
Exam-ready answer points. Define abstract class/method; explain instantiation restriction and override obligation; contrast abstract class vs interface.
Self-check questions with answers.
- Can you instantiate an abstract class? Answer: no.
- Must a non-abstract derived class implement all abstract members? Answer: yes.
12. base Keyword
Plain-language definition and why it matters. base accesses members of the base class from a derived class. It matters to call base constructors and base methods that a derived class overrides.
Core theory. base(...) in a constructor initializer calls the base constructor. base.Method() calls the base implementation of an overridden method. Used to extend (not replace) base behavior.
Syntax / notation.
public class Dog : Animal
{
public Dog(string name) : base(name) { } // call base ctor
public override void Speak()
{
base.Speak(); // call Animal.Speak()
Console.WriteLine("bark");
}
}
Worked example. Dog calls base(name) and base.Speak() then adds barking.
Realistic use case. Derived exception classes call base(message) to pass the message to System.Exception.
Comparison table.
| this | base | |
|---|---|---|
| Refers to | current instance | base class |
| Use | this() ctor chaining, disambiguate |
base() ctor, call overridden method |
Common mistakes / limitations. base only in non-static instance members; calling base.Method() on a non-overridden method is still valid (calls base).
Exam-ready answer points. Explain base(...) constructor initializer and base.Method(); contrast with this.
Self-check questions with answers.
- What does
base(name)do in a derived constructor? Answer: calls the base class constructor withname. - Can
basebe used in static members? Answer: no — it refers to a base instance.
13. Overloading
Plain-language definition and why it matters. Overloading lets multiple methods/constructors/operators share a name with different parameters. It matters for convenient, readable APIs (e.g., Print(), Print(string), Print(int)).
Core theory. Overload resolution based on number, type, order of parameters (signature). Return type alone is not enough to overload. Optional parameters can simulate overloads. Constructors commonly overloaded. Operator overloads are a form of overloading.
Syntax / notation.
public void Print() { Print("default"); }
public void Print(string message) { Console.WriteLine(message); }
// usage: Print(); Print("hello");
Worked example. A Logger with Log(), Log(string), Log(string, Level).
Realistic use case. A Convert class with ToInt(string), ToInt(object), ToInt(string, int base).
Comparison table.
| Overloaded by | Not enough alone |
|---|---|
| parameter count/types/order | return type only |
Common mistakes / limitations. Ambiguous calls (compiler can't pick); relying on return type for overloads (illegal); too many overloads confuse.
Exam-ready answer points. Define overloading; signature rules; return type not sufficient; examples with methods/constructors.
Self-check questions with answers.
- Can two methods differ only by return type and overload? Answer: no — signature must differ (parameters).
- What is the signature used for overload resolution? Answer: number, type, and order of parameters.
14. Object Type
Plain-language definition and why it matters. object (alias for System.Object) is the root base class of all types. Every value or reference type can be treated as an object (boxing for value types). It matters for collections/APIs that accept any type.
Core theory. object members available on all: Equals(), GetHashCode(), GetType(), ToString(). Assigning any value to object boxes it (value → heap); unboxing needs a cast and must match the exact type or throws InvalidCastException.
Syntax / notation.
object o = 42; // boxing
int i = (int)o; // unboxing
Console.WriteLine(o.ToString());
object o2 = "hello";
Worked example. A List<object> holding mixed values; cast back to use them.
Realistic use case. Legacy APIs accepting object parameters; modern code uses generics instead (List<T>) to avoid boxing.
Comparison table.
| object | specific type | |
|---|---|---|
| Can hold | any type | one type |
| Boxing | yes (for value types) | no |
| Type safety | low | high |
Common mistakes / limitations. Invalid cast if unboxing wrong type; boxing overhead in loops; prefer generics (List<T>) over List<object>.
Exam-ready answer points. Explain object as root; boxing/unboxing; GetType/ToString; risks.
Self-check questions with answers.
- What is the root class of all C# types? Answer:
object(System.Object). - What happens when you assign an
inttoobject? Answer: boxing (value copied to heap).
15. Structs
Plain-language definition and why it matters. A struct is a value type (lightweight, stack-allocated or inline) for small data groupings. It matters because structs are copied on assignment (no reference sharing) and suit small, immutable data (points, colors, money).
Core theory. struct Point { int X, Y; }. Value type: copied when assigned/passed; no inheritance (structs implement interfaces but can't inherit from classes); cannot be null unless nullable (Point?); default value zero-initialized. Good for small, immutable data; bad for large/frequently-assigned data (copy cost).
Syntax / notation.
public struct Point { public int X; public int Y; }
var p1 = new Point { X = 1, Y = 2 };
var p2 = p1; // copy
p2.X = 99; // p1.X still 1
Worked example. Point struct copy semantics show p1 unaffected by p2 change.
Realistic use case. A geometry library uses Point structs for coordinates.
Comparison table.
| Class | Struct | |
|---|---|---|
| Type | reference | value |
| Assignment | reference copied | value copied |
| Null | yes | no (unless nullable) |
| Inheritance | yes | no |
Common mistakes / limitations. Expecting reference semantics (mutation of one copy doesn't affect another); using structs for large data (copy overhead); mutable structs (surprising behavior).
Exam-ready answer points. Define struct as value type; copy semantics; no inheritance; nullable structs; when to use vs class.
Self-check questions with answers.
- Is a struct a reference or value type? Answer: value type.
- Does assigning one struct to another copy the value? Answer: yes.
16. Access Modifiers
Plain-language definition and why it matters. Access modifiers control who can see/use a type or member. They matter for encapsulation: hide internals, expose only intended API.
Core theory. public (anywhere), private (containing type only), protected (containing + derived), internal (same assembly), protected internal (derived or same assembly), private protected (derived in same assembly), file (C# 11, same file). Default: class members private; classes internal.
Syntax / notation.
public class Account
{
private decimal _balance; // only this class
public decimal Balance { get; } // anywhere
protected void Recalculate() { } // this + derived
internal string Code { get; set; } // same assembly
}
Worked example. Balance private with public getter; Code internal to assembly.
Realistic use case. A library exposes public API and keeps helper methods private/internal.
Comparison table.
| Modifier | Accessible from |
|---|---|
| public | anywhere |
| private | same type |
| protected | same type + derived |
| internal | same assembly |
| protected internal | derived OR same assembly |
Common mistakes / limitations. Making everything public (breaks encapsulation); relying on internal across assemblies (needs InternalsVisibleTo for tests).
Exam-ready answer points. List modifiers and their scope; explain default accessibility; encapsulation rationale.
Self-check questions with answers.
- Which modifier limits access to the same assembly? Answer:
internal. - Can a
privatemember be accessed from a derived class? Answer: no — useprotected.
17. Interfaces
Plain-language definition and why it matters. An interface defines a contract (members) that implementing classes must provide. It matters for polymorphism without inheritance, multiple "capabilities," and decoupling (program to an interface, not a class).
Core theory. interface IName { members } (methods, properties, events, indexers — no implementation in pre-C# 8; C# 8+ allows default interface members). A class implements with class C : IName. Multiple interfaces allowed. is/as check/ cast. Interface variables can hold any implementing object.
Syntax / notation.
public interface IPayable { decimal CalculatePay(); }
public class Employee : IPayable { public decimal CalculatePay() => 5000; }
// usage
IPayable p = new Employee();
decimal pay = p.CalculatePay();
Worked example. IPayable implemented by Employee and Contractor; polymorphic pay calculation.
Realistic use case. A reporting tool iterates IPrintable objects and calls Print() without knowing concrete types.
Comparison table.
| Class inheritance | Interface | |
|---|---|---|
| Relationship | is-a | can-do/capability |
| Count | one base | many |
| State | can have fields | no instance state (pre-C#8) |
Common mistakes / limitations. Forgetting to implement all interface members (compile error); using interfaces when simple inheritance suffices; interface name prefix I convention.
Exam-ready answer points. Define interface; implementation syntax; multiple interfaces; contrast with class inheritance.
Self-check questions with answers.
- Can a class implement multiple interfaces? Answer: yes.
- What is the common C# prefix for interface names? Answer:
I(e.g., IPayable).
18. Enums
Plain-language definition and why it matters. An enum is a distinct type with named constants. It matters for readability and type safety when a value is one of a fixed set (days, statuses, roles).
Core theory. enum Name { A, B, C } — underlying type defaults to int; can specify byte/short/int/long. Values start at 0 unless assigned. FlagsAttribute for bit fields. Convert to/from int with cast; ToString() gives name; Enum.Parse/TryParse from string.
Syntax / notation.
public enum OrderStatus { Pending, Shipped, Delivered }
OrderStatus s = OrderStatus.Shipped; // 1
int v = (int)s; // 1
OrderStatus s2 = (OrderStatus)1; // Shipped
[Flags] public enum Permissions { Read=1, Write=2, Execute=4 }
Worked example. Order status enum used in a switch to display messages.
Realistic use case. A task app uses enum Priority { Low, Medium, High }.
Comparison table.
| Enum | Constants | |
|---|---|---|
| Type safety | distinct type | just ints/strings |
| Grouping | yes | no |
Common mistakes / limitations. Comparing enum to raw int without cast; Flags without powers of two; assuming enum values start at 1 (they start at 0).
Exam-ready answer points. Define enum; underlying int; conversion; Flags; default 0.
Self-check questions with answers.
- What is the default underlying type of an enum? Answer:
int. - What is the first enum value by default? Answer: 0.
19. Generics
Plain-language definition and why it matters. Generics let classes/methods operate with a type parameter (T) specified at use, providing type safety and avoiding boxing. They matter because collections like List<T> and Dictionary<K,V> are the standard .NET collections.
Core theory. List<T>, Dictionary<K,V>, Nullable<T>, IEnumerable<T>. Type parameter supplied at declaration/instantiation (List<int>). Constraints (where T : struct, where T : new(), where T : IComparable). Avoids object/boxing and casts; compile-time type safety. Generic methods: void Swap<T>(ref T a, ref T b).
Syntax / notation.
var names = new List<string> { "Sita", "Ram" };
names.Add("Hari"); // compile error if adding int
Dictionary<int, string> dict = new Dictionary<int, string>();
T Swap<T>(ref T a, ref T b) { T t = a; a = b; b = t; }
Worked example. List<string> only accepts strings; Swap<int> swaps two ints type-safely.
Realistic use case. A repository Repository<T> works with any entity type safely.
Comparison table.
| List | List | |
|---|---|---|
| Type safety | no (casts needed) | yes (compile-time) |
| Boxing | yes for value types | no |
Common mistakes / limitations. Using List<object> and casting (loses safety, boxes); forgetting constraints when calling members on T; covariance confusion (List<string> is not List<object>).
Exam-ready answer points. Explain generic type parameter; List<T>/Dictionary<K,V>; constraints; benefits over object; generic methods.
Self-check questions with answers.
- Why prefer
List<T>overList<object>? Answer: compile-time type safety and no boxing. - Name a generic collection. Answer:
List<T>(orDictionary<K,V>).
Key terms — Unit 3
class · member · field · property · method · constructor · object initializer · constructor overloading · deconstructor · Deconstruct · this · property · getter · setter · auto-property · backing field · indexer · static constructor · static class · finalizer · Dispose · IDisposable · GC.SuppressFinalize · dynamic · var · operator overloading · inheritance · virtual · override · sealed · abstract class · abstract method · base · overloading · signature · object · System.Object · boxing · unboxing · struct · value type · access modifiers · public/private/protected/protected internal/private protected/internal · interface · IPayable · enum · Flags · generics · List · Dictionary<K,V> · constraint · covariance
Unit summary — Unit 3
Classes group fields/properties/methods/events/constructors; constructors initialize (overloading/chaining) and deconstructors split objects. this disambiguates and chains; properties encapsulate with get/set; indexers enable obj[i] syntax. Static constructors initialize once; static classes can't be instantiated; finalizers are GC backups (prefer IDisposable). dynamic defers binding to runtime. Operators can be overloaded (related pairs; == needs Equals/GetHashCode). Inheritance (virtual/override/sealed/abstract, single base, object root) and base calls. Overloading by signature. object is the root (boxing/unboxing risk). Structs are value types (copied, no inheritance). Access modifiers (public/private/protected/internal…) enforce encapsulation. Interfaces define contracts (multiple allowed). Enums are named constants (int-based, Flags). Generics (List<T>, Dictionary<K,V>, constraints) provide type safety without boxing.
Unit 4: Advanced C#
Teaching hours: 14
Topics in outline order
- Delegates
- Events
- Lambda Expressions
- Exception Handling
- Introduction of LINQ
- Working with Databases
- Writing Web Applications using ASP-NET
1. Delegates
Plain-language definition and why it matters. A delegate is a type-safe function pointer — a reference to a method with a matching signature. It matters because delegates enable callbacks, event handling, and passing behavior as data (LINQ, LINQ-to-Objects use delegates under the hood).
Core theory. Declare: delegate int Operation(int a, int b);. Instantiate: Operation op = Add; or op = new Operation(Add);. Invoke: op(2, 3) or op.Invoke(2, 3). Multicast: op += Add; op += Subtract; invokes all (returns last). Built-in: Action (no return), Func<T, TResult> (returns), Predicate<T> (bool). Delegate type must match method signature (covariance/contravariance allowed in modern C#).
Syntax / notation.
delegate int MathOp(int x, int y);
int Add(int a, int b) => a + b;
MathOp op = Add;
int result = op(2, 3); // 5
// multicast
MathOp multi = Add;
multi += (a, b) => a - b;
foreach (var r in multi.GetInvocationList()) { ... }
Worked example. A calculator that accepts an Operation delegate and applies it to two numbers.
Realistic use case. LINQ Where(items, predicate) uses a delegate (Func<Item,bool>) passed by the caller.
Comparison table.
| Delegate | Interface | |
|---|---|---|
| Encapsulates | a method signature | a set of members |
| Use | callbacks, events, LINQ | contracts, polymorphism |
Common mistakes / limitations. Multicast delegate returns only the last result; exceptions in one invocation stop the rest (unless handled); signature mismatch is a compile error.
Exam-ready answer points. Define delegate; declare/invoke; multicast; built-in Action/Func/Predicate; contrast with interfaces.
Self-check questions with answers.
- What is a delegate? Answer: a type-safe reference to a method (function pointer).
- Name a built-in delegate that returns a value. Answer:
Func<T, TResult>(Action returns void; Predicate returns bool).
2. Events
Plain-language definition and why it matters. Events are a publish/subscribe mechanism built on delegates. They let an object (publisher) notify subscribers when something happens. They matter for GUI button clicks and loose coupling.
Core theory. Declare: public event EventHandler<MyArgs> Completed;. Publisher raises: Completed?.Invoke(this, args); (null-conditional). Subscribers: obj.Completed += Handler;. EventHandler<TEventArgs> signature: void(object sender, TEventArgs e). Custom event args derive from EventArgs. Fields-like access restricted: only publisher can +=/-= and invoke from within class; outside can only subscribe/unsubscribe.
Syntax / notation.
public class Button
{
public event EventHandler Click;
public void OnClick() => Click?.Invoke(this, EventArgs.Empty);
}
// subscriber
button.Click += (s, e) => Console.WriteLine("clicked");
Worked example. Button click event: subscriber lambda prints when clicked; publisher raises safely with ?.Invoke.
Realistic use case. A OrderPlaced event notifies email, inventory, and analytics services without the order class knowing them.
Comparison table.
| Delegate | Event | |
|---|---|---|
| Direct invocation | yes (any holder) | only publisher (protected) |
| Model | callback | publish/subscribe |
Common mistakes / limitations. Raising a null event (use ?.Invoke or check null); subscribers forgetting to unsubscribe (memory leak if publisher outlives subscriber); making events public fields (use event keyword to restrict).
Exam-ready answer points. Explain event declaration, subscription (+=), raising (?.Invoke), EventHandler<TEventArgs>, publisher/subscriber roles.
Self-check questions with answers.
- How do you safely raise an event? Answer:
eventName?.Invoke(sender, args);(null-conditional). - Which keyword restricts invocation to the publisher? Answer:
event.
3. Lambda Expressions
Plain-language definition and why it matters. Lambda expressions are anonymous functions (params) => expression/body. They matter because they're concise delegates used heavily in LINQ, events, and Action/Func.
Core theory. Syntax: input => expression (expression body) or input => { statements; } (statement block). Type inference usually determines parameter types. Can capture outer variables (closure). Statement lambdas can contain multiple statements; expression lambdas return a value implicitly. async lambdas: async () => await ....
Syntax / notation.
Func<int, int> square = x => x * x; // expression
Func<int, int, int> add = (a, b) => a + b; // multiple params
Action log = () => Console.WriteLine("log"); // no params
Worked example. numbers.Where(n => n > 5) filters with a lambda predicate.
Realistic use case. Event handler button.Click += (s, e) => ... without a separate method.
Comparison table.
| Anonymous method | Lambda | |
|---|---|---|
| Syntax | delegate(int x) { ... } |
x => ... |
| Conciseness | more verbose | concise |
Common mistakes / limitations. Capturing a loop variable in a lambda (closure pitfalls in older C#); expression lambda can't contain statements; overusing lambdas harms readability.
Exam-ready answer points. Define lambda; show expression vs statement body; type inference; closure/capture note; use in delegates/LINQ.
Self-check questions with answers.
- What does
x => x * xmean? Answer: a lambda takingxand returningx*x. - Can a lambda capture outer variables? Answer: yes (closure).
4. Exception Handling
Plain-language definition and why it matters. Exception handling manages runtime errors gracefully so the program doesn't crash. It matters for robust enterprise code: report, log, recover, or fail safely.
Core theory. try { ... } catch (ExceptionType ex) { ... } finally { ... }. throw to raise; throw ex resets stack trace (use throw; to preserve). Specific exceptions before general (catch (DivideByZeroException) then catch (Exception)). Custom exceptions derive from Exception. finally always runs (cleanup). Checked vs unchecked (C# exceptions are unchecked — no compile requirement to declare). Exception, ArgumentException, InvalidOperationException, NullReferenceException, DivideByZeroException, IOException.
Syntax / notation.
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero");
throw; // preserve stack trace
}
finally
{
Console.WriteLine("cleanup");
}
Worked example. Divide with zero check and finally cleanup.
Realistic use case. File reading: try open/read, catch IOException, finally close stream (or use using).
Comparison table.
| Block | Runs when |
|---|---|
| try | the guarded code |
| catch | an exception of matching type occurs |
| finally | always (after try/catch) |
Common mistakes / limitations. Catching Exception too broadly and swallowing errors; throw ex loses stack trace (use throw); empty catch blocks (hide bugs); not using finally/using for cleanup.
Exam-ready answer points. Explain try/catch/finally; ordering specific→general; throw; vs throw ex; custom exceptions; finally always runs.
Self-check questions with answers.
- Does
finallyalways run? Answer: yes, whether or not an exception occurred (unless process terminates). - Should you use
throw exorthrow;? Answer:throw;preserves the original stack trace.
5. Introduction of LINQ
Plain-language definition and why it matters. LINQ (Language Integrated Query) is a set of extensions for querying collections, databases, XML with consistent C# syntax. It matters because it replaces manual loops with readable, composable queries (where, select, orderby).
Core theory. Query syntax: from x in list where x > 5 select x. Method syntax: list.Where(x => x > 5).Select(x => x). Extension methods in System.Linq (Where, Select, OrderBy, First, Count, Sum, GroupBy, Join). Deferred execution: query built but not run until enumerated (foreach, ToList). IEnumerable<T> and IQueryable<T> (LINQ-to-Objects vs LINQ-to-SQL/Entities).
Syntax / notation.
using System.Linq;
var query = from n in numbers where n > 5 select n;
// method syntax
var q2 = numbers.Where(n => n > 5).Select(n => n * 2);
foreach (var x in query) { ... } // execution happens here
Worked example. Filter and project numbers with query syntax and method syntax; show same result.
Realistic use case. Querying an in-memory list of orders: orders.Where(o => o.Total > 1000).Select(o => o.Customer).
Comparison table.
| Query syntax | Method syntax | |
|---|---|---|
| Style | SQL-like from/where/select |
extension methods + lambdas |
| Readability | often clearer for joins/grouping | more flexible |
Common mistakes / limitations. Assuming immediate execution (deferred execution means DB/query runs at enumeration — can cause multiple executions); mixing query and method poorly; First() throws if empty (use FirstOrDefault).
Exam-ready answer points. Define LINQ; show query and method syntax; name common operators; explain deferred execution; First() vs FirstOrDefault().
Self-check questions with answers.
- What does
Wheredo in LINQ? Answer: filters elements by a predicate. - What is deferred execution? Answer: the query runs when enumerated, not when defined.
6. Working with Databases
Plain-language definition and why it matters. .NET works with databases via ADO.NET (direct) or Entity Framework (ORM). Working with databases means connecting, executing commands, reading results, and handling data. It matters because most enterprise apps persist data.
Core theory. ADO.NET: SqlConnection (connect), SqlCommand (execute SQL), SqlDataReader (read forward-only), SqlDataAdapter/DataSet (disconnected). Connection string in config. Parameterized queries (@name) prevent SQL injection. using ensures connection/command/reader disposal. Entity Framework: DbContext, DbSet<T>, LINQ-to-Entities, change tracking, SaveChanges(). SQL basics: SELECT, INSERT, UPDATE, DELETE, WHERE, parameters.
Syntax / notation. ADO.NET:
using var conn = new SqlConnection(connectionString);
using var cmd = new SqlCommand("SELECT Name FROM Customers WHERE Id = @id", conn);
cmd.Parameters.AddWithValue("@id", id);
conn.Open();
using var reader = cmd.ExecuteReader();
while (reader.Read()) Console.WriteLine(reader.GetString(0));
Worked example. Query a customer by ID with parameterized SqlCommand, read with SqlDataReader, all wrapped in using.
Realistic use case. A customer screen looks up a record by ID safely (parameterized, no SQL injection).
Comparison table.
| ADO.NET | Entity Framework | |
|---|---|---|
| Approach | direct SQL, manual mapping | ORM, LINQ-to-Entities, auto-mapping |
| Control | high | less (convention-based) |
| Boilerplate | more | less |
Common mistakes / limitations. String-concatenating SQL (injection); not disposing connections (pool exhaustion); SqlDataReader must be closed before using the connection again; N+1 queries in EF.
Exam-ready answer points. Explain ADO.NET objects (Connection, Command, DataReader); parameterized queries; using; contrast ADO.NET vs Entity Framework; SQL injection prevention.
Self-check questions with answers.
- Why use parameterized queries (
@id)? Answer: prevent SQL injection and handle values safely. - Which ADO.NET class reads forward-only results? Answer:
SqlDataReader.
7. Writing Web Applications using ASP-NET
Plain-language definition and why it matters. ASP.NET is Microsoft's framework for server-side web applications and services. Writing ASP.NET apps means handling HTTP requests, generating responses, and (in MVC/Web API) separating concerns. It matters because web apps are a primary .NET use case.
Core theory. ASP.NET (Web Forms, MVC, Web API) and ASP.NET Core (cross-platform). Request → routing → controller/action → view/model → response. MVC pattern: Model (data), View (UI), Controller (input → model → view). Razor view engine (@model, @Html). Startup/Program.cs configures services and middleware pipeline. State: session, query string, POST form. Web API returns JSON/XML.
Syntax / notation. Razor: @model Customer then @Model.Name. Controller: public IActionResult Index() { return View(); }. Routing attribute: [Route("api/customers")].
Worked example. MVC controller action returning a view with a model; Razor rendering @Model.Name.
Realistic use case. An online store: product catalog (MVC views), shopping cart (session), checkout API (Web API JSON).
Comparison table.
| ASP.NET (Framework) | ASP.NET Core | |
|---|---|---|
| Platform | Windows | cross-platform |
| Model | Web Forms/MVC/Web API | MVC/Web API (unified), Razor Pages |
| Open source | partially | fully |
Common mistakes / limitations. Confusing ASP.NET (Windows-only, older) with ASP.NET Core (cross-platform, modern); not sanitizing user input in Razor (XSS risk); hardcoding connection strings.
Exam-ready answer points. Explain ASP.NET request flow, MVC roles, Razor, routing; contrast ASP.NET vs ASP.NET Core; mention state (session/POST/query).
Self-check questions with answers.
- What does MVC stand for and what does the Controller do? Answer: Model-View-Controller; Controller handles input, works with Model, selects View.
- Which is cross-platform: ASP.NET or ASP.NET Core? Answer: ASP.NET Core.
Key terms — Unit 4
delegate · Action · Func · Predicate · multicast · event · EventHandler · publisher · subscriber · += · ?.Invoke · lambda · expression body · statement body · closure · try · catch · finally · throw · throw; · NullReferenceException · DivideByZeroException · IOException · LINQ · Where · Select · OrderBy · First · FirstOrDefault · deferred execution · IEnumerable · IQueryable · ADO.NET · SqlConnection · SqlCommand · SqlDataReader · parameterized query · SQL injection · DbContext · DbSet · SaveChanges · ASP.NET · ASP.NET Core · MVC · Model · View · Controller · Razor · routing · Web API · JSON
Unit summary — Unit 4
Delegates are type-safe method references (built-in Action/Func/Predicate, multicast). Events are publisher/subscriber notifications built on delegates (+=, ?.Invoke, EventHandler<TEventArgs>). Lambda expressions (x => expr) are concise anonymous functions with closures. Exception handling uses try/catch/finally, throw; to preserve stack traces, specific-before-general catch. LINQ queries collections with query/method syntax (Where, Select, deferred execution). Databases via ADO.NET (SqlConnection/Command/DataReader, parameterized queries vs injection) or Entity Framework (DbContext, SaveChanges). ASP.NET builds server web apps (MVC/Web API, Razor); ASP.NET Core is cross-platform/modern.
Key terms (full course)
object orientation · encapsulation · inheritance · polymorphism · abstraction · type safety · boxing · unboxing · Garbage Collector · generations · IDisposable · using · .NET Framework · .NET Core · .NET 5+ · Mono · .NET Standard · .NET Standard 2.0 · CLR · IL · JIT · assembly · metadata · FCL/BCL · C# · VB.NET · F# · WPF · WCF · ASP.NET · ASP.NET Core · Entity Framework · NuGet · Main · Console · GUI · identifier · keyword · comment · XML doc · data type · value type · reference type · decimal · string · StringBuilder · array · variable · parameter · ref · out · params · const · readonly · statement · if · switch · for · foreach · while · break · continue · return · namespace · using · class · constructor · deconstructor · this · property · indexer · static · finalizer · dynamic · operator overloading · virtual · override · sealed · abstract · base · object · struct · access modifier · interface · enum · generics · List · Dictionary<K,V> · constraint · delegate · Action · Func · event · lambda · exception · try · catch · finally · LINQ · ADO.NET · SqlConnection · SqlCommand · SqlDataReader · DbContext · SaveChanges · MVC · Razor · Web API
Unit summary (full course)
Unit 1: .NET foundations — OOP, type safety, GC memory management, platform support, C#/CLR/IL/JIT, .NET Framework vs .NET Core vs .NET Standard, applied technologies. Unit 2: C# basics — console/GUI, identifiers, comments, data types, operators, strings, arrays, variables/parameters, statements, namespaces. Unit 3: Creating types — classes, constructors/deconstructors, this, properties, indexers, static/finalizer, dynamic binding, operator overloading, inheritance, abstract, base, overloading, object, structs, access modifiers, interfaces, enums, generics. Unit 4: Advanced C# — delegates, events, lambdas, exception handling, LINQ, databases (ADO.NET/Entity Framework), ASP.NET web apps.
Detailed practice questions and answer keys
-
Explain object orientation's four pillars and show a C# class with encapsulation. Answer: Encapsulation (private field + public property), inheritance (
class B : A), polymorphism (virtual/override), abstraction (abstract/interface). Example:public class Account { private decimal _bal; public decimal Balance { get => _bal; } public void Deposit(decimal a) => _bal += a; }. -
Describe value vs reference types and when to use
decimal. Answer: Value types (int, double, decimal, bool, char, struct, enum) are copied; reference types (class, string, array, delegate) are referenced. Usedecimalfor money (exact precision), notdouble. -
Write a property with validation and explain why not a public field. Answer:
public decimal Price { get => _price; set { if (value<0) throw; _price=value; } }— properties validate/encapsulate; public fields expose raw state. -
Explain inheritance with
virtual/overrideand thebasekeyword. Answer:class Dog : Animal; basevirtual void Speak(), derivedoverride void Speak();base(...)calls base constructor;base.Method()calls base implementation. C# = single class inheritance. -
Contrast interface vs abstract class. Answer: Interface = contract, no instance state (pre-C#8), multiple allowed. Abstract class = partial implementation + fields, single base, can't be instantiated.
-
Write a LINQ query and explain deferred execution. Answer:
var q = from n in nums where n > 5 select n;ornums.Where(n => n>5). Deferred = runs when enumerated (foreach/ToList), not when defined. -
Show an ADO.NET parameterized query and explain SQL injection prevention. Answer:
new SqlCommand("SELECT ... WHERE Id = @id", conn); cmd.Parameters.AddWithValue("@id", id);— parameters are treated as values, not executable SQL, so injection is blocked. -
Describe the ASP.NET MVC pattern and contrast ASP.NET vs ASP.NET Core. Answer: Model = data, View = UI, Controller = input → model → view. ASP.NET = Windows-only (Web Forms/MVC/Web API); ASP.NET Core = cross-platform, open-source, unified.
References from the source syllabus
- TU document: https://portal.tu.edu.np/downloads/BCA_Syllabus-compressed_compre_2024_01_30_18_33_22.pdf
- Location: PDF p. 79-81
- Source file: the course outline
- SHA-256: sha256:06a38e2bb817239afc0f4edac703e14ffa2dd1cac8236d1260e239fae019d741
- Original course code: CACS302; mapped course code: BCA405-I; curriculum key: 2018; semester: 5.
- Class load: 6 Hrs./Week (Theory: 3 Hrs., Practical: 3 Hrs.); Credits: 3.
Note: The 2018 curriculum key cites older TU source material; confirm the edition before publication. Source wording preserved where it differs from modern spelling (e.g., "Consturctors", "ASP-NET"). This guide is a mapped archived outline and is not a new 2025 detailed syllabus.
Content audit (metadata)
- Unit count: 4
- Topic count: 47 (Unit 1: 10, Unit 2: 10, Unit 3: 19, Unit 4: 7; matches the mapped archived outline)
- Covered topic count: 47
- Word count: ~15,200
- Status: staged (every TOC topic has substantive content)
- Unresolved items: Verify course code mapping, contact hours, and edition against an official TU source before publication; source retains original spellings ("Consturctors", "ASP-NET") noted above.
- Label: mapped archived outline (2018 curriculum); not a new 2025 detailed syllabus.