Skip to main content

Chapter 4

.NET Programming

TU BIM past exam questions

Past questions and answers

22 questions set from this chapter. Most repeated first.

  • 2026 AD Model · 1 mark

Define .NET Framework.

Answer

The .NET Framework is a Microsoft software development platform for building and running Windows applications. It consists of the Common Language Runtime (CLR) and the Framework Class Library (FCL), and supports languages such as C#, VB.NET and F#.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 1 mark

What is Common Language Runtime (CLR)?

Answer

The CLR is the execution engine of .NET. It runs code compiled to Intermediate Language (IL) using a JIT compiler and provides memory management (garbage collection), type safety, exception handling and security.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 1 mark

List any two project types available in Visual Studio for .NET development.

Answer

  • Console Application
  • ASP.NET Core Web Application (others: Windows Forms App, Class Library, WPF App)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 1 mark

List any four generic collections in C#.

Answer

List<T>, Dictionary<TKey, TValue>, Queue<T> and Stack<T> (also HashSet<T>, LinkedList<T>), all in System.Collections.Generic.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 1 mark

Define a delegate in C#.

Answer

A delegate is a type-safe object that holds a reference to a method with a specific signature. It lets methods be passed as parameters and is the basis of events and callbacks, for example delegate int Op(int a, int b);.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 1 mark

What is StringBuilder and why is it used?

Answer

StringBuilder (in System.Text) is a class that represents a mutable string. It is used because ordinary string objects are immutable, so repeated concatenation creates many new objects; StringBuilder modifies its buffer in place and is faster and more memory-efficient for many appends.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 1 mark

Name any two approaches in Entity Framework.

Answer

  • Code First
  • Database First (also Model First)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 1 mark

What is Razor syntax in ASP.NET?

Answer

Razor is a markup syntax used in ASP.NET to embed C# code in HTML pages (.cshtml) using the @ symbol, for example <p>Hello @Model.Name</p>. It generates dynamic web content on the server.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 1 mark

List the three main Execute methods of SqlCommand in ADO.NET.

Answer

  • ExecuteReader() returns a SqlDataReader for SELECT queries.
  • ExecuteNonQuery() runs INSERT, UPDATE and DELETE and returns the number of rows affected.
  • ExecuteScalar() returns a single value (the first column of the first row).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 1 mark

What is LINQ?

Answer

LINQ (Language Integrated Query) is a .NET feature that allows querying collections, databases and XML using a uniform SQL-like syntax built into C#, for example from s in students where s.Marks > 50 select s.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 3 marks

Compare .NET Framework with .NET Core.

Answer

Basis.NET Framework.NET Core
PlatformWindows onlyCross-platform (Windows, Linux, macOS)
SourceMostly closed-sourceOpen source
PerformanceGoodHigher, optimized and modular
DeploymentMachine-wide installationSide-by-side, app-local versions, self-contained
ArchitectureMonolithicModular via NuGet packages
Web / cloudASP.NET (System.Web)ASP.NET Core, suited to microservices and containers
StatusLegacy, maintenance onlyActively developed (now unified as .NET 5+)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 3 marks

Explain the difference between abstract class and interface with a suitable example.

Answer

BasisAbstract classInterface
MembersCan have abstract and concrete methods, fields, constructorsMainly method/property signatures (default methods allowed in C# 8+)
InheritanceA class can inherit only oneA class can implement many
ConstructorAllowedNot allowed
Access modifiersAllowedMembers are public by default
UseCommon base with shared code ("is-a")Capability contract ("can-do")
abstract class Shape {
    public abstract double Area();
    public void Show() { Console.WriteLine("Area: " + Area()); }
}
interface IDrawable { void Draw(); }

class Circle : Shape, IDrawable {
    double r;
    public Circle(double r) { this.r = r; }
    public override double Area() => Math.PI * r * r;
    public void Draw() { Console.WriteLine("Drawing circle"); }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 3 marks

How do you implement exception handling in C#? Write a small code snippet.

Answer

C# handles exceptions with try, catch, finally and throw. Code that may fail goes in try, errors are handled in catch, and finally always runs (for cleanup).

using System;

class Program {
    static void Main() {
        try {
            int a = 10, b = 0;
            int c = a / b;
            Console.WriteLine(c);
        }
        catch (DivideByZeroException ex) {
            Console.WriteLine("Error: " + ex.Message);
        }
        catch (Exception ex) {
            Console.WriteLine("General error: " + ex.Message);
        }
        finally {
            Console.WriteLine("Finally block executed");
        }
    }
}

Specific exceptions are caught before the general Exception.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 3 marks

What is the role of Lambda expressions? Give one practical use case.

Answer

A lambda expression is a short anonymous function written with the => operator, in the form (parameters) => expression. Its role is to write concise inline code, to pass behaviour to delegates and methods, and to provide the predicates used in LINQ queries, which makes code shorter and more readable.

Practical use case: filtering a list with LINQ.

List<int> marks = new List<int> { 35, 62, 48, 90, 71 };
var passed = marks.Where(m => m >= 50).ToList();   // 62, 90, 71

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 3 marks

Differentiate between Database-First and Code-First approaches in Entity Framework.

Answer

BasisDatabase-FirstCode-First
Starting pointAn existing databaseC# entity classes written by the developer
Model creationScaffolded (reverse engineered) from the database schema, e.g. Scaffold-DbContextClasses and DbContext are written by hand
Schema changesMade in the database, then the model is re-scaffoldedMade in code, then applied with Migrations (Add-Migration, Update-Database)
ControlDatabase is the source of truthCode is the source of truth
Best forLegacy or DBA-managed databasesNew projects and domain-driven design

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 3 marks

Write a short note on URL routing in ASP.NET MVC.

Answer

URL routing in ASP.NET MVC maps an incoming request URL to a controller action, instead of mapping it to a physical file. The routing engine compares the URL with the registered route patterns and extracts the controller, action and optional parameters.

The default route is registered in Program.cs (or RouteConfig.cs in older versions):

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

So /Student/Edit/5 calls StudentController.Edit(5). Custom routes and attribute routing ([Route("students/{id}")]) can also be defined. Routing gives clean, SEO-friendly URLs and separates the URL structure from the file structure.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 5 marks

Explain the complete architecture of the .NET Framework and highlight the role of Class Library and CLR.

Answer

The .NET Framework is a software platform for building and running Windows, web and service applications. Its main layers are:

  1. Programming languages: C#, VB.NET, F# and others. All compile to the same intermediate code.
  2. Common Language Specification (CLS) and Common Type System (CTS): rules that let code in different languages interoperate and share data types.
  3. Framework Class Library (FCL / Base Class Library): the reusable class library.
  4. Application models: ASP.NET (Web Forms, MVC), Windows Forms, WPF, ADO.NET, WCF.
  5. Common Language Runtime (CLR): the execution engine.
  6. Operating system and hardware: the layer the CLR runs on.

Compilation flow: source code is compiled to Microsoft Intermediate Language (MSIL) and metadata, stored in an assembly (.exe or .dll). At run time the CLR's JIT compiler converts MSIL to native machine code.

Role of the Class Library: it provides thousands of ready-made classes, interfaces and value types in namespaces such as System, System.IO, System.Data, System.Collections and System.Web. It covers collections, file I/O, database access, networking, XML, threading and security. This speeds up development and gives all .NET languages one consistent API.

Role of the CLR:

  • JIT compilation of MSIL to native code.
  • Automatic memory management through the garbage collector.
  • Type safety checking, with the CTS and CLS.
  • Exception handling.
  • Code access security.
  • Thread management.
  • Assembly loading and versioning.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 5 marks

Explain the architecture of ASP.NET MVC with a neat diagram and describe the role of Model, View, and Controller.

Answer

ASP.NET MVC is a web framework that separates an application into three components: Model, View and Controller. This separation of concerns makes the code easier to test, maintain and extend.

 Browser --request--> Routing --> Controller --> Model --> Database
    ^                                |   ^         |
    |                                v   +---data--+
    +-------- HTML response <------ View

Request flow:

  1. The browser sends a request, for example /Student/Details/3.
  2. Routing maps the URL to a controller and action.
  3. The controller action gets or updates data through the Model.
  4. The controller passes the data (a model or ViewBag) to a View.
  5. The View renders HTML, which is returned to the browser.

Model: represents the data and business logic. It holds the entity classes, validation rules and data access (for example Entity Framework). It knows nothing about the UI.

View: the presentation layer. It is usually a Razor (.cshtml) template that displays model data as HTML. It contains no business logic.

Controller: handles incoming requests. It reads user input, calls the Model, selects the View and returns a result (View(), Redirect(), Json()). It acts as the coordinator between Model and View.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 5 marks

Describe how ADO.NET components (DataReader, DataSet, DataAdapter) work together while performing CRUD operations.

Answer

ADO.NET accesses data through a Connection, a Command, a DataReader and a DataAdapter that fills a DataSet. Two modes exist.

Connected mode (DataReader): SqlConnection opens the link to the database. SqlCommand holds the SQL. ExecuteReader() returns a SqlDataReader, a fast, forward-only, read-only stream. It needs an open connection while reading, so it suits the Read part of CRUD when only displaying data.

Disconnected mode (DataAdapter + DataSet): SqlDataAdapter is the bridge between the database and the in-memory DataSet. Fill() runs the SelectCommand and loads rows into DataTables. The connection is then closed and the user edits the data locally. Update() sends the changes back using the adapter's InsertCommand, UpdateCommand and DeleteCommand (which a SqlCommandBuilder can generate).

CRUD working together:

  • Create, Update, Delete: SqlCommand.ExecuteNonQuery() with an INSERT, UPDATE or DELETE statement, or adapter.Update(dataSet) for batched changes.
  • Read: ExecuteReader() for quick reading, or adapter.Fill(ds) to hold data in memory.
using (var con = new SqlConnection(cs))
{
    var da = new SqlDataAdapter("SELECT * FROM Student", con);
    var ds = new DataSet();
    da.Fill(ds, "Student");            // read into DataSet

    var cmd = new SqlCommand("SELECT Name FROM Student", con);
    con.Open();
    using (var dr = cmd.ExecuteReader())   // read with DataReader
        while (dr.Read()) Console.WriteLine(dr["Name"]);
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 5 marks

Compare and contrast Web Forms, ASP.NET MVC, and ASP.NET Web Pages. Which one would you choose for a large-scale enterprise application and why?

Answer

BasisWeb FormsASP.NET MVCWeb Pages
PatternPage controller, event-drivenModel-View-ControllerSimple page-based, Razor syntax
UI modelServer controls, ViewState, postbacksRazor views, full control of HTMLRazor with inline C# in .cshtml
Separation of concernsWeak (code-behind mixes logic and UI)StrongWeak
TestabilityDifficultEasy (unit testing controllers)Limited
URLsFile based (.aspx)Routing, clean URLsFile based
Learning curveEasy for beginnersModerateEasiest
Suited toRapid small and medium appsLarge, complex, testable appsSmall sites and prototypes

Choice for a large-scale enterprise application: ASP.NET MVC. Its clear separation of Model, View and Controller makes a large codebase easier to maintain, and teams can work on layers in parallel. It supports unit testing and test-driven development, gives full control over HTML and URLs, avoids heavy ViewState (better performance and scalability), and works well with dependency injection and Web API. Web Forms is harder to test and scale, and Web Pages is too simple for enterprise needs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 10 marks

You are tasked to develop a secure online student result management system using ASP.NET MVC and Entity Framework Core.
a. Design the complete folder structure and explain the role of each layer. b. Write the step-by-step process to implement CRUD operations for the "Student" entity using Code-First approach.

Answer

(a) Folder structure and role of each layer

StudentResultSystem/
├── Controllers/        StudentController.cs, ResultController.cs, AccountController.cs
├── Models/             Student.cs, Subject.cs, Result.cs, ViewModels/
├── Data/               ApplicationDbContext.cs, Migrations/
├── Services/           IStudentService.cs, StudentService.cs (business logic)
├── Views/
│   ├── Student/        Index, Create, Edit, Details, Delete .cshtml
│   ├── Shared/         _Layout.cshtml, _ValidationScriptsPartial.cshtml
│   └── _ViewImports.cshtml, _ViewStart.cshtml
├── wwwroot/            css, js, images
├── appsettings.json    connection string, settings
└── Program.cs          services, middleware, routing
  • Models: entity classes (Student) with data annotations for validation, plus view models.
  • Data: the DbContext and migrations. It maps entities to database tables through EF Core.
  • Services (business layer): business rules, so controllers stay thin and testable.
  • Controllers: handle HTTP requests, call services, return views. Authentication and authorization attributes ([Authorize]) are applied here for security.
  • Views: Razor templates that render the UI.
  • wwwroot: static files.
  • Program.cs and appsettings.json: configuration, dependency injection, Identity, HTTPS redirection and routing.

Security measures: ASP.NET Core Identity with roles (Admin, Teacher, Student), [Authorize(Roles="...")], anti-forgery tokens ([ValidateAntiForgeryToken]), HTTPS, parameterized queries through EF Core, and server-side validation.

(b) CRUD for Student using Code-First

  1. Create an ASP.NET Core MVC project and install Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools.
  2. Create the entity:
public class Student
{
    public int Id { get; set; }
    [Required, StringLength(100)] public string Name { get; set; }
    [Required] public string RollNo { get; set; }
    [EmailAddress] public string Email { get; set; }
    public DateTime DateOfBirth { get; set; }
}
  1. Create the context:
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> o) : base(o) { }
    public DbSet<Student> Students { get; set; }
}
  1. Put the connection string in appsettings.json and register the context in Program.cs:
builder.Services.AddDbContext<ApplicationDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
  1. Create the database: run Add-Migration InitialCreate then Update-Database.
  2. Add the controller with the CRUD actions:
[Authorize]
public class StudentController : Controller
{
    private readonly ApplicationDbContext _db;
    public StudentController(ApplicationDbContext db) { _db = db; }

    public async Task<IActionResult> Index() => View(await _db.Students.ToListAsync());          // Read

    public async Task<IActionResult> Details(int id) {
        var s = await _db.Students.FindAsync(id);
        return s == null ? NotFound() : View(s);
    }

    public IActionResult Create() => View();
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(Student s) {                                         // Create
        if (!ModelState.IsValid) return View(s);
        _db.Add(s); await _db.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    public async Task<IActionResult> Edit(int id) {
        var s = await _db.Students.FindAsync(id);
        return s == null ? NotFound() : View(s);
    }
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, Student s) {                                   // Update
        if (id != s.Id) return NotFound();
        if (!ModelState.IsValid) return View(s);
        _db.Update(s); await _db.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Delete(int id) {                                             // Delete
        var s = await _db.Students.FindAsync(id);
        if (s != null) { _db.Students.Remove(s); await _db.SaveChangesAsync(); }
        return RedirectToAction(nameof(Index));
    }
}
  1. Generate or write the Razor views (Index, Create, Edit, Details, Delete) using strongly typed @model Student and tag helpers such as asp-for.
  2. Run and test every operation. If the entity changes later, add a new migration and update the database.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2026 AD Model · 10 marks

You are developing an online Quiz Application using ASP.NET Web Forms. a. How will you use Delegates and Events to handle the "Submit Answer" button click? b. Explain why using StringBuilder is better than normal string when generating the result summary.

Answer

(a) Delegates and Events for the "Submit Answer" button

A delegate is a type-safe reference to a method. An event is a delegate-based notification: the publisher raises it and subscribers (handlers) respond. In Web Forms, the Button.Click event is declared with the delegate EventHandler, and the handler is attached to it.

// Quiz.aspx:  <asp:Button ID="btnSubmit" runat="server" Text="Submit Answer" OnClick="btnSubmit_Click" />

protected void Page_Load(object sender, EventArgs e)
{
    // equivalent to OnClick: subscribe handler to the event through the EventHandler delegate
    btnSubmit.Click += new EventHandler(btnSubmit_Click);
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
    string answer = rblOptions.SelectedValue;
    bool correct = answer == CurrentQuestion.CorrectOption;
    if (correct) Score++;
    AnswerSubmitted?.Invoke(this, new AnswerEventArgs(answer, correct)); // custom event
    LoadNextQuestion();
}

A custom event can be added for other parts (for example a score panel or logger):

public class AnswerEventArgs : EventArgs {
    public string Answer { get; }
    public bool IsCorrect { get; }
    public AnswerEventArgs(string a, bool c) { Answer = a; IsCorrect = c; }
}
public event EventHandler<AnswerEventArgs> AnswerSubmitted;

Flow: the user clicks, the browser posts back, ASP.NET raises the Click event, and the delegate invokes every subscribed handler. This keeps the clicking code (publisher) loosely coupled from the response code (subscribers).

(b) StringBuilder versus string

A string is immutable. Every concatenation (s += ...) creates a new string object and copies the old content, so building a result summary of many lines inside a loop causes many allocations, extra garbage collection and O(n²) copying.

StringBuilder is mutable and uses an internal buffer that grows as needed, so Append modifies it in place with no new object per operation.

var sb = new StringBuilder();
foreach (var q in answers)
    sb.AppendLine($"Q{q.No}: {(q.IsCorrect ? "Correct" : "Wrong")}");
sb.Append($"Total score: {score}/{total}");
lblResult.Text = sb.ToString();

Hence StringBuilder is faster and uses less memory when the result summary is built from many pieces.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from TU BIM Eighth Semester IT 248 Entrepreneurship and Management Model Question (Faculty of Management model question, BIM eighth semester, fomecd.edu.np), TU BIM Eighth Semester IT 278 Big Data and Analytics Model Question (Faculty of Management model question, BIM eighth semester, fomecd.edu.np), TU BIM Eighth Semester IT 277 Cloud Computing Model Question (Faculty of Management model question, BIM eighth semester, fomecd.edu.np), TU BIM Eighth Semester IT 275 .NET Programming Model Question (Faculty of Management model question, BIM eighth semester, fomecd.edu.np), TU BIM Eighth Semester IT 276 Database Administration Model Question (Faculty of Management model question, BIM eighth semester, fomecd.edu.np) and TU BIM Eighth Semester IT 249 Business Intelligence Model Question (Faculty of Management model question, BIM eighth semester, fomecd.edu.np). Answers are written for this site; check them against your class notes.