Skip to main content

Chapter 3

.NET Technology

TU BCA past exam questions

Past questions and answers

59 questions set from this chapter. Most repeated first.

  • 2020 · 5 marks

Differentiate Object Oriented Programming and Object Based Programming. Explain some of the major features of C# language.

Answer

Object Oriented vs Object Based programming

PointObject Oriented (OOP)Object Based
SupportSupports encapsulation, inheritance and polymorphismSupports objects and encapsulation, but not inheritance (and often no polymorphism)
ClassClasses can be derived from other classesNo class inheritance
ReuseCode reuse through inheritanceReuse through composition only
ExamplesC#, Java, C++JavaScript (classic), Visual Basic 6

Major features of C#

  • Object oriented: classes, objects, inheritance, polymorphism, abstraction and encapsulation.
  • Type safe and managed: strong type checking, runs on the CLR with automatic garbage collection, so there are no dangling pointers or memory leaks in normal use.
  • Simple, modern syntax: derived from C/C++ but cleaner, with properties, events, delegates and indexers.
  • Component oriented: properties, methods and events make it easy to build reusable components.
  • Interoperable and versatile: works with other .NET languages, and can build console, web, desktop, mobile and cloud apps.
  • LINQ, generics and lambda expressions: query data in the language itself, with reusable type-safe code.
  • Exception handling and versioning: structured try/catch/finally, and support for versioning of libraries.
  • Asynchronous programming with async and await, and platform independence with modern .NET.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

Explain overview of Microsoft .NET framework and its components in detail.

Answer

Overview of .NET Framework

The Microsoft .NET Framework is a software development platform for building and running Windows, web and service applications. It provides a managed execution environment, a large class library, and supports many languages (C#, VB.NET, F#) which all compile to a common intermediate form so that they can interoperate.

Components

  1. Common Language Runtime (CLR): the execution engine. It loads and runs code, and provides memory management (garbage collection), type safety, exception handling, security and thread management. Source code is compiled to Microsoft Intermediate Language (MSIL/IL), and the JIT compiler converts it to native code at run time.
  2. Framework Class Library (FCL / BCL): a large library of reusable classes and namespaces, such as System, System.IO, System.Collections, System.Data, System.Net, giving support for I/O, collections, networking, data access and more.
  3. Common Type System (CTS): defines the data types (value and reference types) that all .NET languages share, enabling cross-language use of types.
  4. Common Language Specification (CLS): a set of rules that languages must follow to be interoperable.
  5. Application models / technologies: ASP.NET (web), Windows Forms and WPF (desktop), ADO.NET (database access), WCF (services), and LINQ.
  6. Assemblies and metadata: the unit of deployment (.exe or .dll) containing IL code, metadata and a manifest. Assemblies can be placed in the Global Assembly Cache (GAC).

Execution flow: source code -> language compiler -> IL + metadata (assembly) -> CLR (JIT) -> native machine code -> execution.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

What do you mean by property in C# language? How it is different from method? Compare automatic property with other types of property with suitable example.

Answer

Property in C#

A property is a class member that provides a flexible mechanism to read, write or compute the value of a private field. It is accessed like a field, but uses get and set accessors, so it supports encapsulation and allows validation.

class Student
{
    private int age;                 // backing field
    public int Age                   // property
    {
        get { return age; }
        set { if (value > 0) age = value; }
    }
}

Property vs method

PropertyMethod
Accessed like a field, without parentheses (s.Age)Called with parentheses (s.GetAge())
Has get and set accessorsHas a body and may take parameters
Represents data of the objectRepresents behaviour or an action
Cannot take parameters (except indexers)Can take any number of parameters

Types of property and automatic property

  • Read-write property: both get and set.
  • Read-only: only get. Write-only: only set.
  • Computed property: get returns a calculated value.
  • Automatic property: the compiler generates the private backing field.
class Employee
{
    // Automatic property
    public string Name { get; set; }

    // Full property with backing field and validation
    private double salary;
    public double Salary
    {
        get { return salary; }
        set { if (value >= 0) salary = value; }
    }

    // Read-only auto property
    public int Id { get; } = 1;
}

Comparison: an automatic property needs one line and no explicit field, so it is shorter and cleaner, but it cannot contain extra logic such as validation; for that a full property with a backing field is used. Automatic properties can be given different accessibility ({ get; private set; }) and initialisers.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

Define constructor. Explain different types of constructors used in C# with example.

Answer

Constructor

A constructor is a special member method of a class that has the same name as the class, has no return type, and is called automatically when an object is created. It is used to initialise the object's data members.

Types of constructors in C#

  1. Default (parameterless) constructor: takes no arguments. If the class defines none, the compiler provides one.
  2. Parameterized constructor: takes arguments to initialise fields with given values.
  3. Copy constructor: takes an object of the same class and copies its values.
  4. Static constructor: declared with static, has no parameters or access modifiers, runs once automatically before the first use of the class, and initialises static members.
  5. Private constructor: prevents the class from being instantiated from outside (used in singletons and classes with only static members).
using System;

class Student
{
    public int Id;
    public string Name;
    public static int Count;

    static Student() { Count = 0; }               // static constructor

    public Student()                              // default
    {
        Id = 0; Name = "Unknown"; Count++;
    }

    public Student(int id, string name)           // parameterized
    {
        Id = id; Name = name; Count++;
    }

    public Student(Student s)                     // copy
    {
        Id = s.Id; Name = s.Name; Count++;
    }

    static void Main()
    {
        Student a = new Student();
        Student b = new Student(1, "Ram");
        Student c = new Student(b);
        Console.WriteLine(b.Name + " " + c.Name + " " + Student.Count);   // Ram Ram 3
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

a) What is LINQ? Write a program to select employees whose salary is greater than 20000 and whose address is kathmandu using LINQ
b) Write a C# program to show insert and select operation in database.

Answer

(a) LINQ

LINQ (Language Integrated Query) is a feature of C# and .NET that lets you write queries over data sources (collections, arrays, XML, databases) directly in C# using a SQL-like syntax or method syntax, with compile-time checking and IntelliSense.

Program to select employees with salary greater than 20000 and address Kathmandu:

using System;
using System.Collections.Generic;
using System.Linq;

class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Salary { get; set; }
    public string Address { get; set; }
}

class Program
{
    static void Main()
    {
        List<Employee> employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Ram",  Salary = 25000, Address = "Kathmandu" },
            new Employee { Id = 2, Name = "Sita", Salary = 18000, Address = "Kathmandu" },
            new Employee { Id = 3, Name = "Hari", Salary = 30000, Address = "Pokhara" },
            new Employee { Id = 4, Name = "Gita", Salary = 22000, Address = "Kathmandu" }
        };

        var result = from e in employees
                     where e.Salary > 20000 && e.Address == "Kathmandu"
                     select e;

        foreach (var e in result)
            Console.WriteLine(e.Id + " " + e.Name + " " + e.Salary + " " + e.Address);
    }
}

Output: Ram (25000) and Gita (22000).

(b) Insert and select in a database (ADO.NET, SQL Server)

Assume a table Student(Id int, Name varchar(50)).

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string cs = "Data Source=.;Initial Catalog=SchoolDB;Integrated Security=True";

        using (SqlConnection con = new SqlConnection(cs))
        {
            con.Open();

            // Insert
            string insert = "INSERT INTO Student (Id, Name) VALUES (@id, @name)";
            using (SqlCommand cmd = new SqlCommand(insert, con))
            {
                cmd.Parameters.AddWithValue("@id", 1);
                cmd.Parameters.AddWithValue("@name", "Ram");
                int rows = cmd.ExecuteNonQuery();
                Console.WriteLine(rows + " row inserted");
            }

            // Select
            string select = "SELECT Id, Name FROM Student";
            using (SqlCommand cmd = new SqlCommand(select, con))
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                    Console.WriteLine(reader["Id"] + " " + reader["Name"]);
            }
        }
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

What is generics? List different types of generic classes. Explain delegate with example.

Answer

Generics

Generics allow classes, structures, interfaces and methods to be written with a placeholder for the data type (a type parameter such as T), which is specified when the class is used. They give type safety, avoid boxing and unboxing, and allow code reuse.

class Box<T>
{
    private T item;
    public void Set(T value) { item = value; }
    public T Get() { return item; }
}
// Box<int> b = new Box<int>(); b.Set(5);

Generic classes (collections) in System.Collections.Generic

  • List<T>: a resizable list.
  • Dictionary<TKey, TValue>: key-value pairs.
  • Queue<T>: first-in first-out.
  • Stack<T>: last-in first-out.
  • HashSet<T> and SortedSet<T>: unique elements.
  • LinkedList<T>, SortedList<TKey, TValue>, SortedDictionary<TKey, TValue>.

Delegate

A delegate is a type-safe reference to a method. It holds the address of one or more methods that have a matching signature (return type and parameters), so methods can be passed as arguments and called indirectly. Delegates are the basis of events and callbacks. A delegate can be single-cast or multicast (+= adds a method).

using System;

delegate int Operation(int a, int b);        // declaration

class Program
{
    static int Add(int a, int b) { return a + b; }
    static int Multiply(int a, int b) { return a * b; }

    static void Main()
    {
        Operation op = Add;                  // instantiate
        Console.WriteLine(op(3, 4));         // 7

        op = Multiply;
        Console.WriteLine(op(3, 4));         // 12
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

What do you mean by lambda expression? Explain different types of lambda expression used in C# with example.

Answer

A lambda expression is an anonymous (unnamed) function written with the lambda operator => ("goes to"). The left side holds the input parameters and the right side holds the expression or statement block. It can be assigned to a delegate or expression tree and is heavily used with LINQ.

Types of lambda expressions

  1. Expression lambda: the body is a single expression.
Func<int, int> square = x => x * x;
Console.WriteLine(square(5));   // 25
  1. Statement lambda: the body is a block of statements in braces.
Action<string> greet = name => {
    string msg = "Hello, " + name;
    Console.WriteLine(msg);
};
greet("Ram");
  1. Lambda with multiple parameters / no parameters:
Func<int, int, int> add = (a, b) => a + b;
Action hello = () => Console.WriteLine("Hello");
  1. Lambda used with LINQ methods:
int[] nums = { 1, 2, 3, 4, 5, 6 };
var even = nums.Where(n => n % 2 == 0);   // 2 4 6
  1. Expression-bodied members and async lambdas are other forms (public int Sq(int x) => x * x;).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 10 marks

a) Write a program to create user registration form in one ASP.NET web page and display filled data in another page.
b) Write a program for handling exception in ASP.NET

Answer

(a) User registration in two pages.

Register.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<html>
<body>
<form id="form1" runat="server">
    Name: <asp:TextBox ID="txtName" runat="server" /><br />
    Email: <asp:TextBox ID="txtEmail" runat="server" /><br />
    Password: <asp:TextBox ID="txtPass" runat="server" TextMode="Password" /><br />
    Gender:
    <asp:RadioButtonList ID="rblGender" runat="server" RepeatDirection="Horizontal">
        <asp:ListItem>Male</asp:ListItem>
        <asp:ListItem>Female</asp:ListItem>
    </asp:RadioButtonList>
    Country:
    <asp:DropDownList ID="ddlCountry" runat="server">
        <asp:ListItem>Nepal</asp:ListItem>
        <asp:ListItem>India</asp:ListItem>
    </asp:DropDownList><br />
    <asp:Button ID="btnSubmit" runat="server" Text="Register" OnClick="btnSubmit_Click" />
</form>
</body>
</html>

Register.aspx.cs:

public partial class Register : System.Web.UI.Page {
    protected void btnSubmit_Click(object sender, EventArgs e) {
        Session["name"] = txtName.Text;
        Session["email"] = txtEmail.Text;
        Session["gender"] = rblGender.SelectedValue;
        Session["country"] = ddlCountry.SelectedValue;
        Response.Redirect("Display.aspx");
    }
}

Display.aspx.cs (page has a Label lblInfo):

public partial class Display : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        lblInfo.Text = "Name: " + Session["name"] + "<br/>Email: " + Session["email"] +
                       "<br/>Gender: " + Session["gender"] + "<br/>Country: " + Session["country"];
    }
}

(b) Exception handling in ASP.NET, with try-catch-finally in the page and a page-level Page_Error handler (and Application_Error in Global.asax):

protected void btnDivide_Click(object sender, EventArgs e) {
    try {
        int a = int.Parse(txtA.Text);
        int b = int.Parse(txtB.Text);
        lblResult.Text = "Result: " + (a / b);
    }
    catch (FormatException) {
        lblResult.Text = "Please enter valid numbers.";
    }
    catch (DivideByZeroException) {
        lblResult.Text = "Divisor cannot be zero.";
    }
    catch (Exception ex) {
        lblResult.Text = "Error: " + ex.Message;
    }
    finally {
        // cleanup code
    }
}

protected void Page_Error(object sender, EventArgs e) {
    Exception ex = Server.GetLastError();
    Response.Write("Unhandled error: " + ex.Message);
    Server.ClearError();
}

Custom error pages can also be set in web.config with <customErrors mode="On" defaultRedirect="Error.aspx" />.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 10 marks

a) How virtual method is used to achieve dynamic binding in C#? Explain with the help of suitable program.
b) Define operator overloading. Write a C# program to overload binary operator.

Answer

(a) A virtual method is declared in the base class with virtual and can be redefined in a derived class with override. When a base-class reference points to a derived object, the method actually called is decided at run time from the object's real type. This is dynamic binding (late binding / run-time polymorphism).

using System;
class Shape {
    public virtual void Draw() { Console.WriteLine("Drawing a shape"); }
}
class Circle : Shape {
    public override void Draw() { Console.WriteLine("Drawing a circle"); }
}
class Rectangle : Shape {
    public override void Draw() { Console.WriteLine("Drawing a rectangle"); }
}
class Program {
    static void Main() {
        Shape s;
        s = new Circle();    s.Draw();   // Drawing a circle
        s = new Rectangle(); s.Draw();   // Drawing a rectangle
        s = new Shape();     s.Draw();   // Drawing a shape
    }
}

The reference type is always Shape, yet the overridden version is selected at run time through the virtual method table.

(b) Operator overloading means giving an existing operator (such as +, -, ==) a new meaning for a user-defined type by defining a public static method named operator <symbol>. Binary operators take two operands.

using System;
class Complex {
    public int Real, Imag;
    public Complex(int r, int i) { Real = r; Imag = i; }
    public static Complex operator +(Complex a, Complex b) {
        return new Complex(a.Real + b.Real, a.Imag + b.Imag);
    }
    public static Complex operator -(Complex a, Complex b) {
        return new Complex(a.Real - b.Real, a.Imag - b.Imag);
    }
    public void Show() { Console.WriteLine(Real + " + " + Imag + "i"); }
}
class Program {
    static void Main() {
        Complex c1 = new Complex(3, 4), c2 = new Complex(1, 2);
        (c1 + c2).Show();   // 4 + 6i
        (c1 - c2).Show();   // 2 + 2i
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What is CLR? List and explain the feature of CLR.

Answer

The Common Language Runtime (CLR) is the execution engine of the .NET Framework. It runs managed code: it loads assemblies, converts MSIL to native machine code using the JIT compiler and provides runtime services to the program.

Features of CLR

  1. Language interoperability: code written in different .NET languages can call each other because all compile to MSIL and share the CTS.
  2. JIT compilation: MSIL is compiled to native code at run time, method by method, when first called, and cached.
  3. Automatic memory management: the garbage collector frees unused objects, avoiding memory leaks.
  4. Type safety and verification: the CLR checks code and types so that memory cannot be accessed illegally.
  5. Exception handling: a uniform structured exception mechanism across languages.
  6. Code access security: permissions and verification control what code is allowed to do.
  7. Thread management: supports multithreading and thread pooling.
  8. Versioning and deployment: assemblies carry version information, which removes "DLL hell"; side-by-side execution is supported.
  9. Cross-platform support (through implementations such as .NET Core/.NET and Mono) and debugging/profiling services.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What do you mean by value type and reference type? Give an example for each.

Answer

Value type: a variable directly contains its data, usually stored on the stack. Assigning one variable to another copies the value, so changes to one do not affect the other. Value types derive from System.ValueType. Examples: int, float, double, char, bool, struct, enum.

int a = 10;
int b = a;     // copy
b = 20;        // a is still 10

Reference type: a variable holds a reference (address) to data stored on the managed heap. Assigning copies the reference, so both variables refer to the same object and a change through one is seen through the other. Default value is null. Examples: class, string, array, interface, delegate, object.

class Person { public string Name; }
Person p1 = new Person { Name = "Ram" };
Person p2 = p1;        // same object
p2.Name = "Shyam";     // p1.Name is also "Shyam"

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What is an interface? How interface is used in multiple inheritance? Explain with example.

Answer

An interface is a contract that contains only declarations of members (methods, properties, events, indexers) with no implementation (in classic C#). It is declared with the interface keyword, conventionally named with a leading I. A class or struct that implements it must provide all of its members, and all members are public by default.

Multiple inheritance through interfaces: C# does not allow a class to inherit from more than one class, but a class can implement any number of interfaces. This gives the effect of multiple inheritance without ambiguity problems.

using System;
interface IPrintable { void Print(); }
interface IScannable { void Scan(); }

class Machine : IPrintable, IScannable {
    public void Print() { Console.WriteLine("Printing document"); }
    public void Scan()  { Console.WriteLine("Scanning document"); }
}
class Program {
    static void Main() {
        Machine m = new Machine();
        m.Print();
        m.Scan();
        IPrintable p = m;   // interface reference
        p.Print();
    }
}

If two interfaces have a member with the same name, the class can use explicit implementation (void IPrintable.Print()) to separate them.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

Why namespace is used in C#? How to create and use the namespace in C#? Explain with example.

Answer

A namespace is a container that groups related classes, interfaces, structs, enums and delegates under one name.

Why it is used

  • Organises code logically in large projects.
  • Avoids name conflicts, since two classes with the same name can exist in different namespaces.
  • Gives controlled access to library classes (e.g. System.IO).

Creating a namespace: use the namespace keyword. Namespaces can be nested.

Using a namespace: with the fully qualified name, or with a using directive (an alias can also be defined).

using System;

namespace College {
    namespace Library {
        public class Book {
            public void Show() { Console.WriteLine("Book from Library"); }
        }
    }
    public class Student {
        public void Show() { Console.WriteLine("Student of College"); }
    }
}
namespace TestApp {
    using College.Library;          // using directive
    class Program {
        static void Main() {
            Book b = new Book();
            b.Show();
            College.Student s = new College.Student();   // fully qualified name
            s.Show();
        }
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What is an Exception? Write a program to generate divide by zero exception and index out of Range exception and also handle these exception.

Answer

An exception is a run-time error or abnormal condition that disrupts the normal flow of a program (for example, dividing by zero or accessing an invalid array index). In C# an exception is an object of a class derived from System.Exception, and it is handled using try, catch, finally and throw.

using System;
class Program {
    static void Main() {
        try {
            int a = 10, b = 0;
            Console.WriteLine(a / b);          // DivideByZeroException
        }
        catch (DivideByZeroException ex) {
            Console.WriteLine("Error: " + ex.Message);
        }

        try {
            int[] arr = new int[3] { 1, 2, 3 };
            Console.WriteLine(arr[5]);         // IndexOutOfRangeException
        }
        catch (IndexOutOfRangeException ex) {
            Console.WriteLine("Error: " + ex.Message);
        }
        finally {
            Console.WriteLine("Finished.");
        }
    }
}

The finally block always executes, whether or not an exception occurs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What is a Query expression? Write a C# program to select Students who are lived in Kirtipur and studied in Patan Multiple Campus using LINQ.

Answer

A query expression is a query written in LINQ query syntax, which looks like SQL: it begins with a from clause and ends with a select or group clause, with optional where, orderby, join and let clauses between. The compiler translates it into standard query operator method calls.

using System;
using System.Linq;
using System.Collections.Generic;

class Student {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Campus { get; set; }
}
class Program {
    static void Main() {
        List<Student> students = new List<Student> {
            new Student { Id = 1, Name = "Ram",  Address = "Kirtipur",  Campus = "Patan Multiple Campus" },
            new Student { Id = 2, Name = "Sita", Address = "Lalitpur",  Campus = "Patan Multiple Campus" },
            new Student { Id = 3, Name = "Hari", Address = "Kirtipur",  Campus = "Tri-Chandra Campus" },
            new Student { Id = 4, Name = "Gita", Address = "Kirtipur",  Campus = "Patan Multiple Campus" }
        };
        var result = from s in students
                     where s.Address == "Kirtipur" && s.Campus == "Patan Multiple Campus"
                     select s;
        foreach (var s in result)
            Console.WriteLine(s.Id + " " + s.Name + " " + s.Address + " " + s.Campus);
    }
}

Output: Ram and Gita.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What do you mean by static class and constructor? Explain with suitable example.

Answer

Static class: a class declared with the static keyword. It cannot be instantiated or inherited and contains only static members. It is sealed implicitly. It is used for utility functions that need no object state (e.g. Math, Console).

Static constructor: a constructor declared static, with no access modifier and no parameters. It initialises static data and runs automatically once, before the first instance is created or any static member is accessed. It cannot be called directly.

using System;
static class MathUtil {
    public static readonly double Pi;
    static MathUtil() {                       // static constructor
        Pi = 3.14159;
        Console.WriteLine("Static constructor called");
    }
    public static double Area(double r) { return Pi * r * r; }
}
class Program {
    static void Main() {
        Console.WriteLine(MathUtil.Area(2));  // static constructor runs first, then 12.56636
        // MathUtil m = new MathUtil();       // error: cannot instantiate a static class
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 10 marks

What do you mean by Operator Overloading? Write a C# program to demonstrate binary and relational operator overloading.

Answer

Operator overloading is giving an existing operator a new meaning for a user-defined class or struct by defining a public static method with the operator keyword. Binary operators take two parameters; relational operators must be overloaded in pairs (== with !=, < with >, <= with >=) and return bool. When == is overloaded, Equals and GetHashCode should also be overridden.

using System;
class Distance {
    public int Meter;
    public Distance(int m) { Meter = m; }

    // binary operators
    public static Distance operator +(Distance a, Distance b) { return new Distance(a.Meter + b.Meter); }
    public static Distance operator -(Distance a, Distance b) { return new Distance(a.Meter - b.Meter); }

    // relational operators (in pairs)
    public static bool operator >(Distance a, Distance b)  { return a.Meter > b.Meter; }
    public static bool operator <(Distance a, Distance b)  { return a.Meter < b.Meter; }
    public static bool operator ==(Distance a, Distance b) { return a.Meter == b.Meter; }
    public static bool operator !=(Distance a, Distance b) { return a.Meter != b.Meter; }

    public override bool Equals(object o) { return o is Distance d && d.Meter == Meter; }
    public override int GetHashCode() { return Meter.GetHashCode(); }
}
class Program {
    static void Main() {
        Distance d1 = new Distance(50), d2 = new Distance(30);
        Console.WriteLine("Sum = " + (d1 + d2).Meter);          // 80
        Console.WriteLine("Difference = " + (d1 - d2).Meter);   // 20
        Console.WriteLine("d1 > d2 : " + (d1 > d2));            // True
        Console.WriteLine("d1 < d2 : " + (d1 < d2));            // False
        Console.WriteLine("d1 == d2 : " + (d1 == d2));          // False
        Console.WriteLine("d1 != d2 : " + (d1 != d2));          // True
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 10 marks

Explain difference between ExecuteReader and ExecuteNonQuery. Provided that a mysql database named "Company" with table named "Product" with following columns (ProductId as int, ProductName as varchar(20), and UnitPrice as float). Write a C# program to connect to the database and display product records that have UnitPrice is greater than RS. 1000 and update the product record (such as Unit Price 4500) from ProductId whose ProductId=50.

Answer

Difference between ExecuteReader and ExecuteNonQuery

ExecuteReader()ExecuteNonQuery()
Used for SELECT queries that return rowsUsed for INSERT, UPDATE, DELETE and DDL commands
Returns a DataReader object (forward-only, read-only stream)Returns an int: the number of rows affected
Rows are read with Read()No rows are returned

Program (MySQL, using the MySql.Data connector):

using System;
using MySql.Data.MySqlClient;

class Program {
    static void Main() {
        string cs = "server=localhost;user id=root;password=;database=Company";
        using (MySqlConnection con = new MySqlConnection(cs)) {
            con.Open();

            // display products with UnitPrice > 1000
            MySqlCommand sel = new MySqlCommand(
                "SELECT ProductId, ProductName, UnitPrice FROM Product WHERE UnitPrice > 1000", con);
            using (MySqlDataReader dr = sel.ExecuteReader()) {
                while (dr.Read())
                    Console.WriteLine(dr["ProductId"] + "\t" + dr["ProductName"] + "\t" + dr["UnitPrice"]);
            }

            // update UnitPrice to 4500 for ProductId = 50
            MySqlCommand upd = new MySqlCommand(
                "UPDATE Product SET UnitPrice = @price WHERE ProductId = @id", con);
            upd.Parameters.AddWithValue("@price", 4500);
            upd.Parameters.AddWithValue("@id", 50);
            int n = upd.ExecuteNonQuery();
            Console.WriteLine(n + " record(s) updated");
        }
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 10 marks

What is web server control in ASP.NET? List five web server control used in ASP.NET. Write a program to create student registration form in one ASP.NET page and display the filled data within another page.

Answer

Web server controls are ASP.NET controls declared with the asp: prefix and runat="server". They are processed on the server, expose properties, methods and events to server-side code, maintain their state through view state, and render the appropriate HTML to the browser.

Five common web server controls: TextBox, Button, Label, DropDownList, RadioButtonList (others: CheckBox, GridView, ListBox).

Student registration in two pages

StudentReg.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="StudentReg.aspx.cs" Inherits="StudentReg" %>
<html>
<body>
<form id="form1" runat="server">
    Roll No: <asp:TextBox ID="txtRoll" runat="server" /><br />
    Name: <asp:TextBox ID="txtName" runat="server" /><br />
    Address: <asp:TextBox ID="txtAddress" runat="server" /><br />
    Gender:
    <asp:RadioButtonList ID="rblGender" runat="server">
        <asp:ListItem>Male</asp:ListItem>
        <asp:ListItem>Female</asp:ListItem>
    </asp:RadioButtonList>
    Program:
    <asp:DropDownList ID="ddlProgram" runat="server">
        <asp:ListItem>BCA</asp:ListItem>
        <asp:ListItem>BBA</asp:ListItem>
        <asp:ListItem>BIT</asp:ListItem>
    </asp:DropDownList><br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</form>
</body>
</html>

StudentReg.aspx.cs:

public partial class StudentReg : System.Web.UI.Page {
    protected void btnSubmit_Click(object sender, EventArgs e) {
        Response.Redirect("ShowData.aspx?roll=" + Server.UrlEncode(txtRoll.Text) +
            "&name=" + Server.UrlEncode(txtName.Text) +
            "&address=" + Server.UrlEncode(txtAddress.Text) +
            "&gender=" + rblGender.SelectedValue +
            "&program=" + ddlProgram.SelectedValue);
    }
}

ShowData.aspx.cs (page contains Label lblData):

public partial class ShowData : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        lblData.Text = "Roll No: " + Request.QueryString["roll"] +
            "<br/>Name: " + Request.QueryString["name"] +
            "<br/>Address: " + Request.QueryString["address"] +
            "<br/>Gender: " + Request.QueryString["gender"] +
            "<br/>Program: " + Request.QueryString["program"];
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What do you mean by "safe" programming language? Explain any four applied technologies in DotNet framework.

Answer

"Safe" programming language: a language that prevents the programmer from performing operations that can corrupt memory or crash the system. It checks array bounds, forbids unrestricted pointer arithmetic, initialises variables, performs type checking and manages memory automatically through garbage collection. C# running under the CLR is safe, because code is verified and managed; direct pointer use is allowed only inside explicitly unsafe blocks.

Four applied technologies in the .NET framework

  1. ASP.NET: framework for building dynamic web sites, web applications and web APIs using server controls, Web Forms/MVC and code-behind.
  2. ADO.NET: data access technology for connecting to databases, executing commands, and working with DataSet, DataReader and DataAdapter.
  3. Windows Forms / WPF: for building rich desktop GUI applications; WPF uses XAML and vector-based rendering.
  4. WCF (Windows Communication Foundation): for building distributed, service-oriented applications that communicate through SOAP, REST and other protocols.

(LINQ and Entity Framework are other applied technologies.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

List any five canonical keywords in "C#". Write a C# program to initialize and display array element with sum of each power.

Answer

Five canonical (keyword) examples in C#: class, static, public, void, namespace (others: int, if, for, new, using, string, return). Keywords are reserved words with a fixed meaning for the compiler and cannot be used as identifiers.

Program: initialise an array and display each element with the sum of its powers. Here each element is shown with its square and cube, and the sum of those powers.

using System;
class Program {
    static void Main() {
        int[] arr = { 1, 2, 3, 4, 5 };
        Console.WriteLine("Element\tSquare\tCube\tSum of powers");
        foreach (int x in arr) {
            double sq = Math.Pow(x, 2);
            double cu = Math.Pow(x, 3);
            Console.WriteLine(x + "\t" + sq + "\t" + cu + "\t" + (x + sq + cu));
        }
    }
}

For element 3 the output is 3,9,273, 9, 27 and sum 3+9+27=393 + 9 + 27 = 39.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is string interpolation? How passing argument by value is differing from passing argument by reference? Explain with program.

Answer

String interpolation is a way of building strings by embedding expressions directly inside a string literal prefixed with $, with the expressions in curly braces.

string name = "Ram"; int age = 20;
Console.WriteLine($"Name: {name}, Age: {age}, Next year: {age + 1}");

It is easier to read than string.Format or concatenation.

Pass by value vs pass by reference

Pass by valuePass by reference
A copy of the argument is passedThe variable's address is passed (using ref or out)
Changes inside the method do not affect the caller's variableChanges are reflected in the caller's variable
Default in C#Requires ref/out keyword in both declaration and call
using System;
class Program {
    static void ByValue(int x) { x = x + 10; }
    static void ByRef(ref int x) { x = x + 10; }
    static void Main() {
        int a = 5, b = 5;
        ByValue(a);
        ByRef(ref b);
        Console.WriteLine($"a = {a}");   // 5  (unchanged)
        Console.WriteLine($"b = {b}");   // 15 (changed)
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What are sealed classes in C#? Write a C# program to illustrate the concept of abstract class and abstract method.

Answer

A sealed class is declared with the sealed keyword and cannot be inherited. It is used to stop further derivation, for security or design reasons (e.g. string is sealed). A method override can also be sealed to prevent further overriding.

sealed class Final { }
// class Child : Final { }   // error: cannot derive from sealed class

Abstract class and abstract method: an abstract class cannot be instantiated; it may contain abstract methods (declaration only, no body) which derived classes must override, as well as ordinary methods.

using System;
abstract class Shape {
    public abstract double Area();            // abstract method
    public void Display() { Console.WriteLine("Area = " + Area()); }
}
class Circle : Shape {
    double r;
    public Circle(double r) { this.r = r; }
    public override double Area() { return Math.PI * r * r; }
}
class Rectangle : Shape {
    double l, b;
    public Rectangle(double l, double b) { this.l = l; this.b = b; }
    public override double Area() { return l * b; }
}
class Program {
    static void Main() {
        Shape s1 = new Circle(2);
        Shape s2 = new Rectangle(4, 5);
        s1.Display();   // Area = 12.566...
        s2.Display();   // Area = 20
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is virtual method? Write a program to illustrate multi-level inheritance with virtual method.

Answer

A virtual method is a base-class method declared with virtual that derived classes may redefine using override. The version executed is chosen at run time according to the actual object type (run-time polymorphism).

Multi-level inheritance with virtual method

using System;
class Animal {
    public virtual void Sound() { Console.WriteLine("Animal makes a sound"); }
}
class Dog : Animal {
    public override void Sound() { Console.WriteLine("Dog barks"); }
}
class Puppy : Dog {
    public override void Sound() { Console.WriteLine("Puppy whines"); }
}
class Program {
    static void Main() {
        Animal a = new Animal(); a.Sound();   // Animal makes a sound
        a = new Dog();           a.Sound();   // Dog barks
        a = new Puppy();         a.Sound();   // Puppy whines
    }
}

Here Puppy inherits from Dog, which inherits from Animal (three levels). The call a.Sound() is resolved at run time to the most derived override.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is different between index and properties? Explain the concept of generic class in C# with 8 suitable program.

Answer

Difference between indexer and property

IndexerProperty
Lets an object be accessed like an array using obj[i]Accessed by name: obj.Name
Declared with this[parameters]Declared with a name
Takes at least one index parameterTakes no parameters
Cannot be staticCan be static
Can be overloaded by parameter listCannot be overloaded
class Names {
    string[] data = new string[3];
    public string this[int i] { get { return data[i]; } set { data[i] = value; } }  // indexer
    public int Count { get { return data.Length; } }                                // property
}

Generic class: a class defined with a type parameter T, so one definition works for any data type with type safety and no boxing.

using System;
class MyStack<T> {
    T[] items = new T[10];
    int top = -1;
    public void Push(T item) { items[++top] = item; }
    public T Pop() { return items[top--]; }
    public bool IsEmpty() { return top == -1; }
}
class Program {
    static void Main() {
        MyStack<int> s1 = new MyStack<int>();
        s1.Push(10); s1.Push(20);
        Console.WriteLine(s1.Pop());     // 20

        MyStack<string> s2 = new MyStack<string>();
        s2.Push("Nepal"); s2.Push("Kathmandu");
        Console.WriteLine(s2.Pop());     // Kathmandu
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

Write a program to create form for calculating simple interest in one ASP.NET page and display the simple interest in another page of ASP.NET.

Answer

Simple interest is SI=P×T×R100SI = \dfrac{P \times T \times R}{100}.

SI.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SI.aspx.cs" Inherits="SI" %>
<html>
<body>
<form id="form1" runat="server">
    Principal (Rs): <asp:TextBox ID="txtP" runat="server" /><br />
    Time (years): <asp:TextBox ID="txtT" runat="server" /><br />
    Rate (%): <asp:TextBox ID="txtR" runat="server" /><br />
    <asp:Button ID="btnCalc" runat="server" Text="Calculate" OnClick="btnCalc_Click" />
</form>
</body>
</html>

SI.aspx.cs:

public partial class SI : System.Web.UI.Page {
    protected void btnCalc_Click(object sender, EventArgs e) {
        double p = double.Parse(txtP.Text);
        double t = double.Parse(txtT.Text);
        double r = double.Parse(txtR.Text);
        double si = (p * t * r) / 100;
        Response.Redirect("Result.aspx?si=" + si);
    }
}

Result.aspx.cs (with a Label lblResult):

public partial class Result : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        lblResult.Text = "Simple Interest = Rs " + Request.QueryString["si"];
    }
}

For example, P=10000P = 10000, T=2T = 2, R=5R = 5 gives SI=10000×2×5100=SI = \frac{10000 \times 2 \times 5}{100} = Rs 1000.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 10 marks

a) What is System Exception? Write a C# program that will read balance and withdraw amount from keyboard and display the remaining balance on screen. if balance is greater than withdrawal amount otherwise throw an Application Exception with appropriate message.
b) List any five LINQ standard operators? Write a C# program to compute aggregate salary of 5 employee and then display employee record in descending order with respective employee salary using LINQ.

Answer

(a) System Exception: System.SystemException is the base class for exceptions thrown by the CLR itself at run time, such as DivideByZeroException, NullReferenceException, IndexOutOfRangeException and InvalidCastException. User-defined exceptions derive from ApplicationException/Exception instead.

using System;
class Program {
    static void Main() {
        try {
            Console.Write("Enter balance: ");
            double balance = double.Parse(Console.ReadLine());
            Console.Write("Enter withdraw amount: ");
            double amount = double.Parse(Console.ReadLine());
            if (balance > amount) {
                balance -= amount;
                Console.WriteLine("Remaining balance: " + balance);
            } else {
                throw new ApplicationException("Insufficient balance for withdrawal.");
            }
        }
        catch (ApplicationException ex) {
            Console.WriteLine("Error: " + ex.Message);
        }
        catch (FormatException) {
            Console.WriteLine("Please enter numeric values.");
        }
    }
}

(b) Five LINQ standard query operators: Where (filter), Select (projection), OrderBy/OrderByDescending (sorting), GroupBy (grouping), Sum/Count/Average (aggregation). (Join, First, Contains are others.)

using System;
using System.Linq;
using System.Collections.Generic;

class Employee {
    public int Id { get; set; }
    public string Name { get; set; }
    public double Salary { get; set; }
}
class Program {
    static void Main() {
        List<Employee> emps = new List<Employee> {
            new Employee { Id = 1, Name = "Ram",   Salary = 30000 },
            new Employee { Id = 2, Name = "Sita",  Salary = 45000 },
            new Employee { Id = 3, Name = "Hari",  Salary = 25000 },
            new Employee { Id = 4, Name = "Gita",  Salary = 50000 },
            new Employee { Id = 5, Name = "Shyam", Salary = 35000 }
        };
        double total = emps.Sum(e => e.Salary);
        Console.WriteLine("Aggregate salary: " + total);       // 185000

        var sorted = from e in emps
                     orderby e.Salary descending
                     select e;
        foreach (var e in sorted)
            Console.WriteLine(e.Id + " " + e.Name + " " + e.Salary);
    }
}

Aggregate: 30000+45000+25000+50000+35000=18500030000 + 45000 + 25000 + 50000 + 35000 = 185000.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 10 marks

What are different type of delegate in C#? Write a C# Program to create a class 'Time' which represents time. The class should have three fields for hours, minutes and seconds. It should have constructor to initialize hours, minutes and seconds and method Time() to print current time.
overload following operators
a) +(Add two time objects of 24 hours clock)
b) Compare two time objects

Answer

Types of delegates in C#

  1. Single-cast delegate: refers to one method.
  2. Multicast delegate: holds several methods, combined using += and removed using -=; they are called in order.
  3. Generic delegates (built in): Func<T,...,TResult> (returns a value), Action<T,...> (returns void) and Predicate<T> (returns bool).
  4. Anonymous method / lambda delegates are inline delegate instances.

Program: Time class with operator overloading

using System;
class Time {
    int hours, minutes, seconds;
    public Time(int h, int m, int s) {
        int total = h * 3600 + m * 60 + s;
        total %= 24 * 3600;
        hours = total / 3600; minutes = (total % 3600) / 60; seconds = total % 60;
    }
    public void Display() {                      // prints the time
        Console.WriteLine($"{hours:D2}:{minutes:D2}:{seconds:D2}");
    }
    int ToSeconds() { return hours * 3600 + minutes * 60 + seconds; }

    // (a) add two times on a 24-hour clock
    public static Time operator +(Time a, Time b) {
        return new Time(0, 0, a.ToSeconds() + b.ToSeconds());   // constructor wraps at 24 h
    }
    // (b) compare two times
    public static bool operator >(Time a, Time b)  { return a.ToSeconds() > b.ToSeconds(); }
    public static bool operator <(Time a, Time b)  { return a.ToSeconds() < b.ToSeconds(); }
    public static bool operator ==(Time a, Time b) { return a.ToSeconds() == b.ToSeconds(); }
    public static bool operator !=(Time a, Time b) { return a.ToSeconds() != b.ToSeconds(); }
    public override bool Equals(object o) { return o is Time t && t == this; }
    public override int GetHashCode() { return ToSeconds(); }
}
class Program {
    static void Main() {
        Time t1 = new Time(15, 40, 30);
        Time t2 = new Time(10, 30, 45);
        t1.Display();                    // 15:40:30
        t2.Display();                    // 10:30:45
        Time t3 = t1 + t2;               // 26:11:15 -> wraps to 02:11:15
        t3.Display();
        Console.WriteLine("t1 > t2  : " + (t1 > t2));    // True
        Console.WriteLine("t1 == t2 : " + (t1 == t2));   // False
    }
}

Check: 15:40:30+10:30:45=26:11:1515{:}40{:}30 + 10{:}30{:}45 = 26{:}11{:}15, which on a 24-hour clock is 02:11:1502{:}11{:}15.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 10 marks

What is difference between executeScalar() and executeReader() method? Write a C# program to connect database Bank and insert 5 customer record (Account_no, Name, Address, Balance) in Customer table and Display the customer record whose balance is greater than 5000.

Answer

Difference between ExecuteScalar() and ExecuteReader()

ExecuteScalar()ExecuteReader()
Returns a single value: first column of the first rowReturns a DataReader for all rows and columns
Return type is object (needs casting)Return type is SqlDataReader
Used for aggregates such as COUNT, SUM, MAXUsed to read many records with Read()

Program (SQL Server, database Bank, table Customer(Account_no, Name, Address, Balance)):

using System;
using System.Data.SqlClient;

class Program {
    static void Main() {
        string cs = "Data Source=.;Initial Catalog=Bank;Integrated Security=True";
        using (SqlConnection con = new SqlConnection(cs)) {
            con.Open();

            for (int i = 1; i <= 5; i++) {
                Console.WriteLine("Customer " + i);
                Console.Write("Account no: "); int acc = int.Parse(Console.ReadLine());
                Console.Write("Name: ");       string name = Console.ReadLine();
                Console.Write("Address: ");    string addr = Console.ReadLine();
                Console.Write("Balance: ");    double bal = double.Parse(Console.ReadLine());

                SqlCommand ins = new SqlCommand(
                    "INSERT INTO Customer(Account_no, Name, Address, Balance) VALUES(@a, @n, @d, @b)", con);
                ins.Parameters.AddWithValue("@a", acc);
                ins.Parameters.AddWithValue("@n", name);
                ins.Parameters.AddWithValue("@d", addr);
                ins.Parameters.AddWithValue("@b", bal);
                ins.ExecuteNonQuery();
            }

            SqlCommand sel = new SqlCommand(
                "SELECT Account_no, Name, Address, Balance FROM Customer WHERE Balance > 5000", con);
            using (SqlDataReader dr = sel.ExecuteReader()) {
                Console.WriteLine("Account\tName\tAddress\tBalance");
                while (dr.Read())
                    Console.WriteLine(dr["Account_no"] + "\t" + dr["Name"] + "\t" +
                                      dr["Address"] + "\t" + dr["Balance"]);
            }
        }
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is managed code? Give reason to justify the statement "DOT NET framework is platform independent and Language interoperability".

Answer

Managed code is code whose execution is controlled by the CLR. The compiler produces MSIL, and the CLR provides services such as JIT compilation, garbage collection, type checking, exception handling and security. Code written in C#, VB.NET and F# is managed. Code that runs outside the CLR (e.g. C/C++ native code) is unmanaged.

Platform independence: .NET source code is compiled not to machine code but to platform-neutral MSIL stored in assemblies. The CLR on each platform (Windows, Linux, macOS through .NET Core/.NET or Mono) compiles MSIL to that machine's native code with the JIT compiler. So the same assembly can run wherever a suitable CLR exists.

Language interoperability: every .NET language compiles to the same MSIL and follows the Common Type System (CTS) and Common Language Specification (CLS). Hence a class written in C# can be inherited in VB.NET, and exceptions, types and objects can be shared across languages in one application.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is optional parameter? Write a C# program which stores values in two enumerations, Department and College. It uses two functions to display the data contained in Department and College enumerations.

Answer

Optional parameter: a method parameter that is given a default value in the declaration, so the caller may omit that argument. Optional parameters must come after all required parameters.

static void Greet(string name, string greeting = "Hello") {
    Console.WriteLine(greeting + ", " + name);
}
// Greet("Ram");  Greet("Ram", "Namaste");

Program with enumerations Department and College:

using System;
enum Department { Computer = 1, Management, Science, Education }
enum College { Patan, Tribhuvan, Kathmandu, Pulchowk }

class Program {
    static void ShowDepartment() {
        Console.WriteLine("Departments:");
        foreach (Department d in Enum.GetValues(typeof(Department)))
            Console.WriteLine((int)d + " : " + d);
    }
    static void ShowCollege() {
        Console.WriteLine("Colleges:");
        foreach (College c in Enum.GetValues(typeof(College)))
            Console.WriteLine((int)c + " : " + c);
    }
    static void Main() {
        ShowDepartment();
        ShowCollege();
    }
}

Values not assigned explicitly start at 0 and increase by 1 (Computer = 1 makes the following ones 2, 3, 4).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is difference between value type and reference type in C#? Explain the concept of boxing and unboxing with suitable program.

Answer

Value type vs reference type

BasisValue typeReference type
StorageHolds the data directly; usually on the stack (or inline inside its containing object)Variable holds a reference; the object lives on the managed heap
AssignmentCopies the value, so two independent copies existCopies the reference, so both variables point to the same object
Default valueZero/false (never null, unless Nullable<T>)null
Examplesint, double, bool, char, struct, enumclass, string, array, interface, delegate, object
Memory managementFreed when scope endsReclaimed by the garbage collector
BaseDerives from System.ValueTypeDerives from System.Object

Boxing and unboxing

Boxing is the implicit conversion of a value type to object (or an interface type it implements). The CLR allocates an object on the heap and copies the value into it. Unboxing is the explicit conversion from object back to the value type; it checks that the boxed object is of the right type and copies the value out. A wrong type throws InvalidCastException. Both operations cost time and memory, so they should be avoided in loops (generics help).

using System;

class BoxingDemo
{
    static void Main()
    {
        int num = 123;
        object obj = num;          // boxing: copy of num placed on heap
        num = 456;                 // changes only the stack copy

        int back = (int)obj;       // unboxing: value copied from heap
        Console.WriteLine("num  = " + num);   // 456
        Console.WriteLine("obj  = " + obj);   // 123
        Console.WriteLine("back = " + back);  // 123

        try
        {
            double d = (double)obj;           // wrong type -> exception
        }
        catch (InvalidCastException e)
        {
            Console.WriteLine("Invalid unboxing: " + e.Message);
        }
    }
}

The output shows that obj keeps the old value 123 because boxing made an independent copy.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is interface? Explain with suitable program, how interface can be used to perform multiple inheritance?

Answer

Interface

An interface is a reference type that declares a contract of members (methods, properties, events, indexers) without (traditional) implementation. A class or struct that implements the interface must provide all its members. Interface names conventionally begin with I; members are implicitly public and abstract; an interface cannot be instantiated and has no fields or constructors.

Multiple inheritance through interfaces

C# does not allow a class to inherit from more than one class (to avoid the diamond problem), but a class can implement any number of interfaces. This gives the effect of multiple inheritance of type.

using System;

interface IPrinter
{
    void Print();
}

interface IScanner
{
    void Scan();
}

class MultiFunctionDevice : IPrinter, IScanner
{
    public void Print() { Console.WriteLine("Printing document..."); }
    public void Scan()  { Console.WriteLine("Scanning document..."); }
}

class Program
{
    static void Main()
    {
        MultiFunctionDevice d = new MultiFunctionDevice();
        d.Print();
        d.Scan();

        IPrinter p = d;     // same object seen through each interface
        IScanner s = d;
        p.Print();
        s.Scan();
    }
}

Here MultiFunctionDevice acquires the behaviour of both IPrinter and IScanner. If two interfaces declare a member with the same signature, the class can use explicit implementation (void IPrinter.Print()) to resolve the ambiguity.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What are use of finalizer in C#? Explain with suitable program, how base keyword is used to call member function and constructor of parent class?

Answer

Finalizer

A finalizer (destructor) is a special member, written ~ClassName(), that is called by the garbage collector just before an object's memory is reclaimed. Its uses:

  • Release unmanaged resources (file handles, database connections, window handles, native memory) held by the object.
  • Act as a safety net if the programmer forgets to call Dispose().
  • Perform last-moment clean-up.

Rules: a class can have only one finalizer; it takes no parameters or access modifiers; it cannot be inherited or called explicitly; its timing is non-deterministic (the compiler converts it into an override of Object.Finalize()).

The base keyword

base refers to the parent class from within a derived class. It is used (1) to call a parent constructor using : base(args) and (2) to call a parent method that has been overridden or hidden using base.Method().

using System;

class Person
{
    protected string name;

    public Person(string name)
    {
        this.name = name;
        Console.WriteLine("Person constructor: " + name);
    }

    public virtual void Display()
    {
        Console.WriteLine("Name: " + name);
    }
}

class Student : Person
{
    private int roll;

    public Student(string name, int roll) : base(name)   // calls parent constructor
    {
        this.roll = roll;
        Console.WriteLine("Student constructor");
    }

    public override void Display()
    {
        base.Display();                                   // calls parent method
        Console.WriteLine("Roll: " + roll);
    }

    ~Student()                                            // finalizer
    {
        Console.WriteLine("Student object finalized");
    }
}

class Program
{
    static void Main()
    {
        Student s = new Student("Ram", 5);
        s.Display();
    }
}

Output: the Person constructor runs first, then the Student constructor, then Display() prints the name (via base) and the roll; the finalizer message appears when the object is collected (typically at program exit).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What are keyword used in exception handling? Write a C# program to handle IndexOutOfRangeException and InvalidCastException.

Answer

Keywords used in exception handling

KeywordPurpose
tryEncloses code that may throw an exception
catchHandles a particular exception type thrown in the try block
finallyBlock that always runs (clean-up), whether or not an exception occurred
throwRaises an exception explicitly, or rethrows the current one

(An optional when filter can be added to a catch clause.)

Program handling IndexOutOfRangeException and InvalidCastException

using System;

class Program
{
    static void Main()
    {
        int[] arr = { 10, 20, 30 };
        object obj = "Nepal";

        try
        {
            Console.WriteLine(arr[5]);          // index 5 does not exist
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine("Index error: " + ex.Message);
        }

        try
        {
            int n = (int)obj;                   // string cannot be cast to int
            Console.WriteLine(n);
        }
        catch (InvalidCastException ex)
        {
            Console.WriteLine("Cast error: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Program finished.");
        }
    }
}

The first access of arr[5] throws IndexOutOfRangeException, caught by the first handler. Unboxing a string as int throws InvalidCastException, caught by the second. The finally block runs in all cases.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is query syntax in LINQ? Explain the standard query operators "select", "contains", "orderBy" and "where" in LINQ with suitable examples.

Answer

Query syntax in LINQ

LINQ (Language Integrated Query) lets us query collections, XML, databases, etc. using C# itself. Query syntax is a declarative, SQL-like form that begins with from and ends with select or group by; the compiler translates it into method (extension) calls.

from <range variable> in <data source>
[where <condition>]
[orderby <key> [ascending|descending]]
select <expression>;

Standard query operators

  • select projects each element into a new form (all elements, one property, or a computed value).
  • where filters elements that satisfy a Boolean condition.
  • orderby sorts the result ascending (default) or descending.
  • Contains checks whether a sequence includes a given element; it is a method used in a condition or on the sequence.
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] nums = { 5, 12, 8, 3, 20, 15 };
        List<string> names = new List<string> { "Sita", "Ram", "Hari", "Gita" };

        // where + orderby + select
        var q = from n in nums
                where n > 5
                orderby n descending
                select n * 2;
        Console.WriteLine(string.Join(", ", q));          // 40, 30, 24, 16

        // select (projection) with where
        var upper = from s in names
                    where s.Length == 4
                    select s.ToUpper();
        Console.WriteLine(string.Join(", ", upper));      // SITA, HARI, GITA

        // Contains
        bool has = nums.Contains(8);
        Console.WriteLine(has);                           // True

        var matched = from s in names
                      where new[] { "Ram", "Gita" }.Contains(s)
                      select s;
        Console.WriteLine(string.Join(", ", matched));    // Ram, Gita
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 10 marks

a) What is an event? Explain with suitable program, how event is handled in C#.
b) What is Lambda expression? Explain the concept of generic delegates with suitable program.

Answer

(a) Event and event handling

An event is a notification sent by an object (the publisher) to tell other objects (the subscribers) that something has happened, such as a button click or a threshold being crossed. Events are built on delegates: the event is declared with the event keyword and a delegate type, and only the publisher can raise it, while subscribers attach handlers with += and detach with -=.

Steps to handle an event:

  1. Declare a delegate (or use EventHandler).
  2. Declare the event in the publisher class.
  3. Raise the event when the condition occurs.
  4. Subscribe a handler method in the subscriber.
using System;

class Counter
{
    public delegate void ThresholdHandler(int value);
    public event ThresholdHandler ThresholdReached;      // event declaration

    private int total;
    private int limit;

    public Counter(int limit) { this.limit = limit; }

    public void Add(int x)
    {
        total += x;
        if (total >= limit && ThresholdReached != null)
            ThresholdReached(total);                      // raise event
    }
}

class Program
{
    static void OnThreshold(int value)                    // event handler
    {
        Console.WriteLine("Threshold reached! Total = " + value);
    }

    static void Main()
    {
        Counter c = new Counter(10);
        c.ThresholdReached += OnThreshold;                // subscribe
        c.Add(4);
        c.Add(7);                                         // total 11 -> event fires
    }
}

(b) Lambda expression and generic delegates

A lambda expression is an anonymous function written with the lambda operator => ("goes to"): (parameters) => expression or (parameters) => { statements }. It can be assigned to a delegate or passed as an argument, and is widely used in LINQ.

Generic delegates are delegates defined with type parameters so one declaration works for many types. The framework provides:

  • Func<T1,...,TResult>: returns a value (last type is the return type).
  • Action<T1,...>: returns nothing.
  • Predicate<T>: takes T and returns bool.
  • A custom one: delegate T Operation<T>(T a, T b);
using System;

class Program
{
    delegate T Operation<T>(T a, T b);                    // custom generic delegate

    static void Main()
    {
        Operation<int> add = (a, b) => a + b;
        Operation<string> join = (a, b) => a + " " + b;
        Console.WriteLine(add(3, 4));                     // 7
        Console.WriteLine(join("Education", "Nepal"));    // Education Nepal

        Func<int, int, int> mul = (x, y) => x * y;        // built-in generic delegates
        Action<string> show = s => Console.WriteLine(s);
        Predicate<int> isEven = n => n % 2 == 0;

        show("Product = " + mul(5, 6));                   // 30
        show("Is 8 even? " + isEven(8));                  // True
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 10 marks

How this keyword is used to declare indexer? Write C# program to overload unary (++) and relational (==) operator.

Answer

this keyword and indexer

An indexer lets an object be accessed with array-like [ ] syntax. It is declared like a property but uses the this keyword followed by a parameter list in square brackets, with get and set accessors:

public <type> this[<index type> index] { get {...} set {...} }
class Student
{
    private string[] subjects = new string[3];

    public string this[int i]
    {
        get { return subjects[i]; }
        set { subjects[i] = value; }
    }
}
// usage: s[0] = "Maths";  Console.WriteLine(s[0]);

Overloading unary ++ and relational ==

Operators are overloaded with public static methods using the operator keyword. == must be overloaded together with !=, and it is good practice to override Equals and GetHashCode too. ++ receives the operand and returns the incremented value (the compiler uses it for both prefix and postfix forms).

using System;

class Point
{
    public int X, Y;

    public Point(int x, int y) { X = x; Y = y; }

    public static Point operator ++(Point p)
    {
        return new Point(p.X + 1, p.Y + 1);
    }

    public static bool operator ==(Point a, Point b)
    {
        if (ReferenceEquals(a, null)) return ReferenceEquals(b, null);
        if (ReferenceEquals(b, null)) return false;
        return a.X == b.X && a.Y == b.Y;
    }

    public static bool operator !=(Point a, Point b)
    {
        return !(a == b);
    }

    public override bool Equals(object obj)
    {
        Point p = obj as Point;
        return p != null && this == p;
    }

    public override int GetHashCode() { return X * 31 + Y; }

    public override string ToString() { return "(" + X + ", " + Y + ")"; }
}

class Program
{
    static void Main()
    {
        Point p1 = new Point(2, 3);
        Point p2 = new Point(3, 4);

        Console.WriteLine("p1 == p2 ? " + (p1 == p2));    // False
        p1++;                                             // (3, 4)
        Console.WriteLine("p1 after ++ : " + p1);
        Console.WriteLine("p1 == p2 ? " + (p1 == p2));    // True
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 10 marks

What are component of ASP.NET? Explain various validation server control in ASP.NET with suitable program.

Answer

Components of ASP.NET

ASP.NET is the web application framework of .NET. Its main components are:

  1. Web Forms (pages, .aspx): event-driven pages with a code-behind file.
  2. Server controls: HTML controls, web server controls (TextBox, Button, GridView), validation controls, user controls.
  3. ASP.NET MVC / Web API / Razor Pages: pattern-based alternatives for building sites and services.
  4. ADO.NET and data controls: database access and data binding (SqlDataSource, GridView).
  5. State management: ViewState, Session, Application, Cookies, QueryString.
  6. Configuration (Web.config) and Global.asax: application settings, application/session events.
  7. Security: authentication, authorization, membership and roles.
  8. Caching, master pages, themes: performance and consistent layout.
  9. Web services / HTTP handlers and modules: request pipeline extensions.
  10. CLR and base class library: the runtime on which all of the above executes.

Validation server controls

Validation controls check user input on the client (JavaScript) and again on the server before processing.

ControlPurpose
RequiredFieldValidatorField must not be empty
CompareValidatorCompares to another control or a value (e.g., password confirmation, data type check)
RangeValidatorValue must lie within a minimum and maximum
RegularExpressionValidatorValue must match a pattern (e-mail, phone)
CustomValidatorUser-written client/server validation logic
ValidationSummaryDisplays all error messages together
<form id="form1" runat="server">
    Name: <asp:TextBox ID="txtName" runat="server" />
    <asp:RequiredFieldValidator ID="rfv1" runat="server"
        ControlToValidate="txtName" ErrorMessage="Name is required"
        ForeColor="Red" Display="Dynamic" /><br />

    Age: <asp:TextBox ID="txtAge" runat="server" />
    <asp:RangeValidator ID="rv1" runat="server" ControlToValidate="txtAge"
        MinimumValue="18" MaximumValue="60" Type="Integer"
        ErrorMessage="Age must be 18-60" ForeColor="Red" Display="Dynamic" /><br />

    Email: <asp:TextBox ID="txtEmail" runat="server" />
    <asp:RegularExpressionValidator ID="rev1" runat="server"
        ControlToValidate="txtEmail"
        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
        ErrorMessage="Invalid email" ForeColor="Red" Display="Dynamic" /><br />

    Password: <asp:TextBox ID="txtPw" runat="server" TextMode="Password" /><br />
    Confirm: <asp:TextBox ID="txtPw2" runat="server" TextMode="Password" />
    <asp:CompareValidator ID="cv1" runat="server" ControlToValidate="txtPw2"
        ControlToCompare="txtPw" ErrorMessage="Passwords do not match"
        ForeColor="Red" Display="Dynamic" /><br />

    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    <asp:ValidationSummary ID="vs1" runat="server" ForeColor="Red" />
    <asp:Label ID="lblMsg" runat="server" />
</form>

Code-behind:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
        lblMsg.Text = "Form submitted successfully.";
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is the importance of Garbage collection in .NET framework? Explain .NET Framework architecture with suitable diagram.

Answer

Importance of garbage collection

The garbage collector (GC) is the CLR component that automatically manages heap memory. It finds objects that are no longer reachable from any root (static fields, stack variables, registers) and reclaims their memory. Its importance:

  • Programmers need not free memory manually, preventing memory leaks and dangling pointers.
  • Prevents invalid memory access and double-free errors, making code safer and more reliable.
  • Compacts the heap, removing fragmentation and keeping allocation fast.
  • Uses generations (0, 1, 2) so short-lived objects are collected cheaply and often, long-lived ones rarely.
  • Runs finalizers to release unmanaged resources.

.NET Framework architecture

+-------------------------------------------------------------+
|  Languages: C#   VB.NET   F#   C++/CLI  ...                 |
+-------------------------------------------------------------+
|  Application models: ASP.NET | Windows Forms | WPF | WCF     |
+-------------------------------------------------------------+
|  ADO.NET | XML | LINQ | Networking | IO | Security | ...     |
|            Base Class Library (BCL / FCL)                    |
+-------------------------------------------------------------+
|  Common Language Runtime (CLR)                               |
|   Class loader | JIT compiler | Garbage collector            |
|   Type checker (CTS) | Exception manager | Security manager  |
+-------------------------------------------------------------+
|  Operating System (Windows)                                  |
+-------------------------------------------------------------+

Components:

  • Common Language Specification (CLS): rules every .NET language must follow for interoperability.
  • Common Type System (CTS): defines value and reference types shared by all languages.
  • CIL/MSIL and assemblies: source code is compiled into Microsoft Intermediate Language plus metadata, packaged as an assembly (.exe/.dll).
  • CLR: loads the assembly, the JIT compiler converts IL to native machine code at run time, and the runtime provides memory management (GC), type safety, exception handling, security and threading.
  • Framework Class Library (FCL): reusable classes and namespaces (System, System.IO, System.Data, System.Web).
  • Application layer: Web (ASP.NET), desktop (Windows Forms, WPF), services (WCF).

Execution flow: Source code -> language compiler -> IL + metadata (assembly) -> CLR (JIT) -> native code -> OS.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is variable size array? Write a C# program to create multidimensional array to store the marks of three student in different subjects. First student has marks of 3 subjects, Second student has marks of 4 subjects and Third student has marks of 2 subjects. Display the subject marks and average marks for each student.

Answer

Variable size (jagged) array

A variable size array, called a jagged array in C#, is an array of arrays in which each inner array can have a different length. It is declared as int[][] a = new int[3][]; and each row is then allocated separately, e.g. a[0] = new int[3];. This differs from a rectangular array int[,], where every row has the same length, and it saves memory when rows differ in size.

Program

using System;

class Program
{
    static void Main()
    {
        int[][] marks = new int[3][];
        marks[0] = new int[3];      // first student: 3 subjects
        marks[1] = new int[4];      // second student: 4 subjects
        marks[2] = new int[2];      // third student: 2 subjects

        for (int i = 0; i < marks.Length; i++)
        {
            Console.WriteLine("Enter marks of student " + (i + 1) + ":");
            for (int j = 0; j < marks[i].Length; j++)
            {
                Console.Write("  Subject " + (j + 1) + ": ");
                marks[i][j] = Convert.ToInt32(Console.ReadLine());
            }
        }

        for (int i = 0; i < marks.Length; i++)
        {
            int sum = 0;
            Console.WriteLine("Student " + (i + 1));
            for (int j = 0; j < marks[i].Length; j++)
            {
                Console.WriteLine("  Subject " + (j + 1) + " : " + marks[i][j]);
                sum += marks[i][j];
            }
            double avg = (double)sum / marks[i].Length;
            Console.WriteLine("  Average = " + avg.ToString("F2"));
        }
    }
}

For example, if student 2 scores 60, 70, 80, 90, the sum is 300, and the average is 300/4=75.00300/4 = 75.00.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

Explain concept of static class and static constructor with suitable program.

Answer

Static class

A static class is declared with the static keyword. It cannot be instantiated, cannot be inherited, and can contain only static members. It is used for utility or helper methods that need no object state (for example Math, Console).

Static constructor

A static constructor is used to initialise static data or perform a one-time action. It has no access modifier and no parameters. It is called automatically once, before the first instance is created or any static member is accessed. A class can have only one static constructor and it cannot be called directly.

using System;

static class MathHelper
{
    public static readonly double Pi;
    public static int CallCount;

    // static constructor: runs once automatically
    static MathHelper()
    {
        Pi = 3.14159;
        CallCount = 0;
        Console.WriteLine("Static constructor called");
    }

    public static double CircleArea(double r)
    {
        CallCount++;
        return Pi * r * r;
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(MathHelper.CircleArea(2));
        Console.WriteLine(MathHelper.CircleArea(3));
        Console.WriteLine("Calls: " + MathHelper.CallCount);
    }
}

The message "Static constructor called" is printed only once, before the first call of CircleArea.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is named argument? Explain with suitable program, how to create alias for namespace in C#?

Answer

Named argument

A named argument lets us pass a value to a method by specifying the parameter name (name: value) instead of relying on the position. This makes calls more readable, allows arguments in any order, and can be combined with optional parameters.

using System;

class Program
{
    static void ShowStudent(string name, int age, string city = "Kathmandu")
    {
        Console.WriteLine($"{name}, {age}, {city}");
    }

    static void Main()
    {
        ShowStudent("Ram", 20);                       // positional
        ShowStudent(age: 21, name: "Sita");           // named, any order
        ShowStudent("Hari", city: "Pokhara", age: 22);// mixed
    }
}

Output:

Ram, 20, Kathmandu
Sita, 21, Kathmandu
Hari, 22, Pokhara

Alias for a namespace

An alias is created with the using directive: using AliasName = Namespace;. It shortens long namespace names and resolves name conflicts.

using Col = System.Collections.Generic;
using Sys = System;

class Test
{
    static void Main()
    {
        Col.List<int> list = new Col.List<int>();
        list.Add(10);
        Sys.Console.WriteLine(list[0]);
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is static binding? Write a C# program to add and subtract two complex number using binary operator overloading.

Answer

Static binding

Static binding (early binding, compile-time binding) means the method to be called is decided by the compiler at compile time, from the declared types and signatures. Method overloading, operator overloading, and calls to static, private and non-virtual methods are statically bound. It is faster, but less flexible than dynamic binding.

Program: complex numbers with binary operator overloading

using System;

class Complex
{
    public double Real, Imag;

    public Complex(double r, double i) { Real = r; Imag = i; }

    public static Complex operator +(Complex a, Complex b)
    {
        return new Complex(a.Real + b.Real, a.Imag + b.Imag);
    }

    public static Complex operator -(Complex a, Complex b)
    {
        return new Complex(a.Real - b.Real, a.Imag - b.Imag);
    }

    public void Display()
    {
        Console.WriteLine($"{Real} {(Imag >= 0 ? "+" : "-")} {Math.Abs(Imag)}i");
    }
}

class Program
{
    static void Main()
    {
        Complex c1 = new Complex(5, 4);
        Complex c2 = new Complex(2, 7);

        Complex sum = c1 + c2;
        Complex diff = c1 - c2;

        Console.Write("Sum = ");  sum.Display();   // 7 + 11i
        Console.Write("Difference = "); diff.Display(); // 3 - 3i
    }
}

The compiler resolves + and - to the overloaded operator methods at compile time, which is static binding.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

Why Delegate is used in C#? Write a C# program to select odd and divisible by 3 number from list of number (1-30) using LINQ query.

Answer

Why delegates are used

A delegate is a type-safe reference to a method. It is used to:

  • pass methods as arguments (callbacks);
  • implement events and event handlers;
  • allow flexible, loosely coupled design, where the caller decides which method runs;
  • support anonymous methods, lambda expressions and LINQ (Func, Action, Predicate).

Program: odd numbers divisible by 3 from 1 to 30 using LINQ

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        var numbers = Enumerable.Range(1, 30);

        var result = from n in numbers
                     where n % 2 != 0 && n % 3 == 0
                     select n;

        Console.WriteLine(string.Join(", ", result));
    }
}

Output: 3, 9, 15, 21, 27

The where clause is converted to a Func<int,bool> delegate (a lambda), which shows how delegates are used in LINQ.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

Write short notes on : (any two)
a) Copy constructor
b) Indexer
c) Lambda Expression

Answer

(a) Copy constructor

A copy constructor creates a new object by copying the data of an existing object of the same class. C# does not provide one automatically, so the programmer writes it, taking an object of the same class as parameter.

class Student
{
    public string Name; public int Age;
    public Student(string n, int a) { Name = n; Age = a; }
    public Student(Student s) { Name = s.Name; Age = s.Age; } // copy constructor
}
// Student s2 = new Student(s1);

It gives an independent copy, unlike s2 = s1, which copies only the reference.

(b) Indexer

An indexer allows an object to be accessed like an array using the [] operator. It is declared like a property with the this keyword and index parameter(s), with get and set accessors.

class Week
{
    string[] days = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
    public string this[int i]
    {
        get { return days[i]; }
        set { days[i] = value; }
    }
}
// Week w = new Week(); Console.WriteLine(w[1]); // Mon

(c) Lambda expression

A lambda expression is an anonymous function written with the lambda operator => (goes to): (parameters) => expression or statement block. It can be assigned to delegates or used in LINQ.

Func<int,int> square = x => x * x;
Console.WriteLine(square(5)); // 25
var evens = list.Where(n => n % 2 == 0);

It makes code short and readable and avoids writing a separate named method.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 10 marks

Differentiate between struct and enum. Why do we need to handle the exception? Illustrate with an example with your own customized exception.

Answer

Difference between struct and enum

StructEnum
A value type that groups related data members of different typesA value type that defines a set of named integral constants
Can contain fields, properties, methods, constructorsContains only named constants (with underlying integral type)
Declared with structDeclared with enum
Can implement interfacesCannot implement interfaces or have methods
Example: struct Point { int X, Y; }Example: enum Day { Sun, Mon, Tue }

Why exception handling is needed

An exception is a runtime error (divide by zero, invalid input, file not found, null reference). Without handling, the program terminates abruptly. Exception handling with try, catch, finally and throw:

  • prevents abnormal termination and keeps the program running;
  • separates error-handling code from normal logic;
  • gives meaningful messages to the user;
  • allows resources (files, connections) to be released in finally.

Example with a customized exception

using System;

class InvalidAgeException : Exception
{
    public InvalidAgeException(string message) : base(message) { }
}

class Program
{
    static void CheckAge(int age)
    {
        if (age < 18)
            throw new InvalidAgeException("Age must be 18 or above to vote.");
        Console.WriteLine("Eligible to vote.");
    }

    static void Main()
    {
        try
        {
            Console.Write("Enter age: ");
            int age = int.Parse(Console.ReadLine());
            CheckAge(age);
        }
        catch (InvalidAgeException ex)
        {
            Console.WriteLine("Custom exception: " + ex.Message);
        }
        catch (FormatException)
        {
            Console.WriteLine("Please enter a valid number.");
        }
        finally
        {
            Console.WriteLine("Program finished.");
        }
    }
}

The custom exception class derives from Exception, is thrown with throw when the rule is violated and is caught by its own catch block.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 10 marks

Define generics. Explain it with proper example. How virtual method is used to achieve dynamic binding in C#? Explain with the help of suitable program.

Answer

Generics

Generics allow classes, interfaces, methods and delegates to be defined with a placeholder type parameter (T) whose actual type is given when it is used. Benefits: type safety, code reuse, no boxing/unboxing, and better performance.

using System;

class Stack<T>
{
    private T[] items = new T[10];
    private int top = 0;
    public void Push(T item) { items[top++] = item; }
    public T Pop() { return items[--top]; }
}

class Program
{
    static void Swap<T>(ref T a, ref T b) { T t = a; a = b; b = t; }

    static void Main()
    {
        Stack<int> s1 = new Stack<int>();
        s1.Push(10); s1.Push(20);
        Console.WriteLine(s1.Pop());      // 20

        Stack<string> s2 = new Stack<string>();
        s2.Push("Nepal");
        Console.WriteLine(s2.Pop());      // Nepal

        int x = 1, y = 2;
        Swap<int>(ref x, ref y);
        Console.WriteLine(x + " " + y);   // 2 1
    }
}

Virtual method and dynamic binding

Dynamic (late) binding means the method to execute is decided at run time from the actual type of the object, not the reference type. In C# it is achieved with a virtual method in the base class, overridden with override in the derived classes. A base class reference pointing to a derived object then calls the derived version.

using System;

class Shape
{
    public virtual void Draw() { Console.WriteLine("Drawing a shape"); }
}
class Circle : Shape
{
    public override void Draw() { Console.WriteLine("Drawing a circle"); }
}
class Square : Shape
{
    public override void Draw() { Console.WriteLine("Drawing a square"); }
}

class Program
{
    static void Main()
    {
        Shape s;
        s = new Circle(); s.Draw();   // Drawing a circle
        s = new Square(); s.Draw();   // Drawing a square
        s = new Shape();  s.Draw();   // Drawing a shape
    }
}

The reference s is of type Shape, but the call is resolved at run time through the virtual method table, so the object's actual class decides which Draw() runs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 10 marks

What are differences between Data Adapter and Data Reader in ADO.NET? Suppose you are hired by a reputed software company which is going to design an application for “Employee Management System”. Your responsibility is to design a schema named EMS and create a table named Employee (EmpNo, Name, Email, phone number, Company, Department, Joining Date, and Salary). Write a program to design a ASP.NET form to take input for this table and insert the data into table after clicking the Save button.

Answer

Difference between DataAdapter and DataReader

DataReaderDataAdapter
Connected architecture: needs an open connection while readingDisconnected architecture: fills a DataSet/DataTable, then the connection can be closed
Forward-only and read-onlyData can be navigated in any direction, edited and updated back
Faster, uses less memorySlower, uses more memory
Reads one row at a time with Read()Loads all rows at once using Fill()
Cannot update the databaseCan update the database via Update()

Schema and table

CREATE SCHEMA EMS;
GO
CREATE TABLE EMS.Employee (
    EmpNo       INT PRIMARY KEY,
    Name        VARCHAR(100),
    Email       VARCHAR(100),
    PhoneNumber VARCHAR(15),
    Company     VARCHAR(100),
    Department  VARCHAR(50),
    JoiningDate DATE,
    Salary      DECIMAL(12,2)
);

ASP.NET form (Employee.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Employee.aspx.cs" Inherits="Employee" %>
<html>
<body>
<form id="form1" runat="server">
  EmpNo: <asp:TextBox ID="txtEmpNo" runat="server" /><br />
  Name: <asp:TextBox ID="txtName" runat="server" /><br />
  Email: <asp:TextBox ID="txtEmail" runat="server" /><br />
  Phone: <asp:TextBox ID="txtPhone" runat="server" /><br />
  Company: <asp:TextBox ID="txtCompany" runat="server" /><br />
  Department: <asp:TextBox ID="txtDept" runat="server" /><br />
  Joining Date: <asp:TextBox ID="txtDate" runat="server" TextMode="Date" /><br />
  Salary: <asp:TextBox ID="txtSalary" runat="server" /><br />
  <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
  <asp:Label ID="lblMsg" runat="server" />
</form>
</body>
</html>

Code-behind (Employee.aspx.cs)

using System;
using System.Data.SqlClient;

public partial class Employee : System.Web.UI.Page
{
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string cs = "Data Source=.;Initial Catalog=EmployeeDB;Integrated Security=True";
        string sql = "INSERT INTO EMS.Employee " +
            "(EmpNo, Name, Email, PhoneNumber, Company, Department, JoiningDate, Salary) " +
            "VALUES (@id,@name,@email,@phone,@company,@dept,@date,@salary)";

        using (SqlConnection con = new SqlConnection(cs))
        using (SqlCommand cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue("@id", int.Parse(txtEmpNo.Text));
            cmd.Parameters.AddWithValue("@name", txtName.Text);
            cmd.Parameters.AddWithValue("@email", txtEmail.Text);
            cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
            cmd.Parameters.AddWithValue("@company", txtCompany.Text);
            cmd.Parameters.AddWithValue("@dept", txtDept.Text);
            cmd.Parameters.AddWithValue("@date", DateTime.Parse(txtDate.Text));
            cmd.Parameters.AddWithValue("@salary", decimal.Parse(txtSalary.Text));

            con.Open();
            int rows = cmd.ExecuteNonQuery();
            lblMsg.Text = rows > 0 ? "Record saved successfully." : "Insert failed.";
        }
    }
}

Parameterised queries are used to prevent SQL injection.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 2+3 marks

What are services provided by CLR? Write a C# program to implement any four method of Console class.

Answer

Services provided by CLR

The Common Language Runtime (CLR) is the execution engine of the .NET Framework. Its services are:

  • Code execution: JIT compilation of MSIL into native code.
  • Memory management and garbage collection: automatic allocation and release of memory.
  • Type safety and verification through the Common Type System (CTS).
  • Exception handling across languages.
  • Security: code access security and verification.
  • Thread management and multithreading support.
  • Cross-language interoperability and versioning/deployment support.

Program using four Console methods

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter your name: ");          // Write
        string name = Console.ReadLine();            // ReadLine

        Console.WriteLine("Hello, " + name);         // WriteLine

        Console.Write("Press any key to change colour...");
        ConsoleKeyInfo k = Console.ReadKey();        // ReadKey
        Console.WriteLine();

        Console.ForegroundColor = ConsoleColor.Green; // property
        Console.WriteLine("Key pressed: " + k.KeyChar);
        Console.ResetColor();
        Console.Clear();                              // Clear
    }
}

The methods used are Write(), WriteLine(), ReadLine() and ReadKey() (plus Clear() and ResetColor()).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

Explain the difference between static and instance constructors with suitable example.

Answer

Instance constructor

An instance constructor has the same name as the class and runs each time an object is created with new. It initialises instance members, can take parameters, can be overloaded and can have access modifiers.

Static constructor

A static constructor is declared with static, has no parameters and no access modifier. It is called automatically once, before the first object is created or any static member is used. It initialises static members and cannot be called explicitly.

Instance constructorStatic constructor
Called every time an object is createdCalled only once per class
Initialises instance dataInitialises static data
Can have parameters and be overloadedNo parameters, only one per class
Can have access modifiersNo access modifiers
Called explicitly by newCalled automatically by the CLR
using System;

class Student
{
    public string Name;
    public static int Count;

    static Student()            // static constructor
    {
        Count = 0;
        Console.WriteLine("Static constructor");
    }

    public Student(string n)    // instance constructor
    {
        Name = n;
        Count++;
        Console.WriteLine("Instance constructor for " + n);
    }
}

class Program
{
    static void Main()
    {
        Student a = new Student("Ram");
        Student b = new Student("Sita");
        Console.WriteLine("Total = " + Student.Count);
    }
}

Output: "Static constructor" appears once, "Instance constructor" appears twice, and Total = 2.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 1+4 marks

What is compile-time polymorphism? Write a C# program to implement method overloading concept by computing area of square and circle.

Answer

Compile-time polymorphism

Compile-time (static) polymorphism is when the method to be called is decided at compile time. It is achieved by method overloading (same name, different parameter lists) and operator overloading.

using System;

class Area
{
    // area of square
    public double Calc(double side)
    {
        return side * side;
    }

    // area of circle (different signature: extra parameter)
    public double Calc(double radius, bool isCircle)
    {
        return Math.PI * radius * radius;
    }
}

class Program
{
    static void Main()
    {
        Area a = new Area();
        Console.WriteLine("Area of square (side 4) = " + a.Calc(4));            // 16
        Console.WriteLine("Area of circle (r 3) = " + a.Calc(3, true).ToString("F2")); // 28.27
    }
}

Both methods are named Calc; the compiler chooses between them by the number and types of arguments. Area of square is s2=16s^2 = 16 and of circle πr2=3.14159×9≈28.27\pi r^2 = 3.14159 \times 9 \approx 28.27.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 1+4 marks

What is parameter? Write a C# program to demonstrate the difference between call by value and call by reference by modifying an integer variable using two separate methods.

Answer

Parameter

A parameter is a variable declared in a method's definition that receives the value (argument) supplied when the method is called. Parameters can be passed by value (a copy) or by reference (ref/out, the same variable).

using System;

class Program
{
    static void ByValue(int x)
    {
        x = x + 10;
        Console.WriteLine("Inside ByValue: " + x);
    }

    static void ByRef(ref int x)
    {
        x = x + 10;
        Console.WriteLine("Inside ByRef: " + x);
    }

    static void Main()
    {
        int a = 5;
        ByValue(a);
        Console.WriteLine("After ByValue: " + a);  // 5

        int b = 5;
        ByRef(ref b);
        Console.WriteLine("After ByRef: " + b);    // 15
    }
}

Output:

Inside ByValue: 15
After ByValue: 5
Inside ByRef: 15
After ByRef: 15

In call by value the method changes only a copy, so the original is unchanged. In call by reference the method works on the original variable, so the change persists.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 2+3 marks

Differentiate between abstract class and interface in C#? Write a C# program to develop console calculator application (only for addition, subtraction and division) using multiple inheritance.

Answer

Abstract class vs interface

Abstract classInterface
Can have abstract and concrete (implemented) methodsTraditionally only declarations (default methods allowed in newer C#)
Can have fields and constructorsNo fields or constructors
A class can inherit only one abstract classA class can implement many interfaces
Members can have access modifiersMembers are public by default
Declared with abstract classDeclared with interface

Calculator using multiple inheritance (via interfaces)

C# does not support multiple class inheritance, so it is achieved by implementing multiple interfaces.

using System;

interface IAdd { double Add(double a, double b); }
interface ISubtract { double Subtract(double a, double b); }
interface IDivide { double Divide(double a, double b); }

class Calculator : IAdd, ISubtract, IDivide
{
    public double Add(double a, double b) { return a + b; }
    public double Subtract(double a, double b) { return a - b; }
    public double Divide(double a, double b)
    {
        if (b == 0) throw new DivideByZeroException("Cannot divide by zero");
        return a / b;
    }
}

class Program
{
    static void Main()
    {
        Calculator c = new Calculator();
        Console.Write("Enter first number: ");
        double x = double.Parse(Console.ReadLine());
        Console.Write("Enter second number: ");
        double y = double.Parse(Console.ReadLine());
        Console.Write("Operator (+, -, /): ");
        char op = Console.ReadKey().KeyChar;
        Console.WriteLine();

        try
        {
            switch (op)
            {
                case '+': Console.WriteLine("Result = " + c.Add(x, y)); break;
                case '-': Console.WriteLine("Result = " + c.Subtract(x, y)); break;
                case '/': Console.WriteLine("Result = " + c.Divide(x, y)); break;
                default: Console.WriteLine("Invalid operator"); break;
            }
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 1+4 marks

What is indexer? Write a C# program to display the BCA 5th semester subject name using indexer.

Answer

Indexer

An indexer lets an object be indexed like an array using []. It is declared with the this keyword, an index parameter and get/set accessors.

using System;

class Semester
{
    private string[] subjects =
    {
        ".NET Technology",
        "Introduction to Management",
        "Computer Graphics",
        "Cyber Law and Professional Ethics",
        "Software Engineering"
    };

    public string this[int index]
    {
        get
        {
            if (index >= 0 && index < subjects.Length)
                return subjects[index];
            return "Invalid index";
        }
        set
        {
            if (index >= 0 && index < subjects.Length)
                subjects[index] = value;
        }
    }

    public int Count { get { return subjects.Length; } }
}

class Program
{
    static void Main()
    {
        Semester sem = new Semester();
        Console.WriteLine("BCA 5th Semester Subjects:");
        for (int i = 0; i < sem.Count; i++)
            Console.WriteLine((i + 1) + ". " + sem[i]);
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 1+4 marks

What are pre-built generic delegate? Write a C# program that reads a list of numbers from the user (comma-separated). Convert the inputs into integers and calculate their sum. Use exception handling to catch FormatException for invalid numbers and OverflowException for numbers too large. Display meaningful messages for each exception.

Answer

Pre-built generic delegates

.NET provides ready-made generic delegates in the System namespace so that we need not declare our own:

  • Func<T1,...,TResult>: refers to a method that takes up to 16 inputs and returns a value, e.g. Func<int,int,int>.
  • Action<T1,...>: refers to a method that takes parameters and returns nothing (void).
  • Predicate<T>: refers to a method that takes one parameter and returns bool.

Program

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter numbers separated by commas: ");
        string input = Console.ReadLine();
        string[] parts = input.Split(',');
        long sum = 0;
        int total = 0;

        try
        {
            foreach (string p in parts)
            {
                int n = Convert.ToInt32(p.Trim());   // may throw
                checked { sum += n; }
                total++;
            }
            Console.WriteLine("Sum = " + sum);
        }
        catch (FormatException)
        {
            Console.WriteLine("Error: one of the inputs is not a valid number.");
        }
        catch (OverflowException)
        {
            Console.WriteLine("Error: a number is too large or too small for an integer.");
        }
    }
}

Convert.ToInt32 throws FormatException for text such as "abc" and OverflowException for values beyond the int range (for example 99999999999).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 10 marks

Explain why operator overloading methods in C# must be declared as static. What happens if you try to declare them as instance methods? Write a C# program to create a class Box with properties Length, Width, and Height. It should have constructor to initialize Length, Width, and Height and methods volume(), surfaceArea() to compute volume and area of box. overload following operators
•

Answer

Why operator overloading methods must be static

An operator is not called on a particular object but works on its operands, which are passed as parameters (a + b becomes operator +(a, b)). The method therefore belongs to the type, not to an instance, so C# requires public static. Also, no this reference should be implicitly involved, so that both operands (for binary operators) are treated symmetrically, e.g. 5 * box and box * 5 can both be supported.

If it is declared as an instance method, the compiler gives an error: "User-defined operators must be declared static" (and public).

Program

The question text for the operators is cut off, so the commonly asked operators + (add two boxes), > and < (compare by volume) and ==, != (equality of dimensions) are overloaded.

using System;

class Box
{
    public double Length { get; set; }
    public double Width { get; set; }
    public double Height { get; set; }

    public Box(double l, double w, double h)
    {
        Length = l; Width = w; Height = h;
    }

    public double Volume()
    {
        return Length * Width * Height;
    }

    public double SurfaceArea()
    {
        return 2 * (Length * Width + Width * Height + Height * Length);
    }

    public static Box operator +(Box a, Box b)
    {
        return new Box(a.Length + b.Length, a.Width + b.Width, a.Height + b.Height);
    }

    public static bool operator >(Box a, Box b) { return a.Volume() > b.Volume(); }
    public static bool operator <(Box a, Box b) { return a.Volume() < b.Volume(); }

    public static bool operator ==(Box a, Box b)
    {
        return a.Length == b.Length && a.Width == b.Width && a.Height == b.Height;
    }
    public static bool operator !=(Box a, Box b) { return !(a == b); }

    public override bool Equals(object o) { return o is Box b && this == b; }
    public override int GetHashCode() { return (Length, Width, Height).GetHashCode(); }
}

class Program
{
    static void Main()
    {
        Box b1 = new Box(2, 3, 4);
        Box b2 = new Box(1, 2, 3);

        Console.WriteLine("Volume b1 = " + b1.Volume());            // 24
        Console.WriteLine("Surface area b1 = " + b1.SurfaceArea()); // 52

        Box b3 = b1 + b2;                                           // 3 x 5 x 7
        Console.WriteLine("Volume b3 = " + b3.Volume());            // 105
        Console.WriteLine("b1 > b2 : " + (b1 > b2));                // True
        Console.WriteLine("b1 == b2 : " + (b1 == b2));              // False
    }
}

Check: for b1, volume =2×3×4=24= 2\times3\times4 = 24 and surface area =2(6+12+8)=52= 2(6+12+8) = 52. For b3 =3×5×7= 3\times5\times7, volume =105= 105.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 1+4+5 marks

Which namespace is used for accessing data? Explain method of each key components of ADO.NET. Assume a database name CompanyDB containing Employee table(Eid, Name, Department, Salary).Write a c# program to connect to the database and insert 5 employee records and display the employee record from CompanyDB database having highest and lowest salary.

Answer

Namespace

Data is accessed using System.Data (with System.Data.SqlClient for SQL Server, or Microsoft.Data.SqlClient in newer versions).

Key components of ADO.NET and their methods

  • Connection (SqlConnection): establishes the link to the database. Methods: Open(), Close(), BeginTransaction().
  • Command (SqlCommand): executes SQL or stored procedures. Methods: ExecuteNonQuery() (insert/update/delete), ExecuteReader() (rows), ExecuteScalar() (single value).
  • DataReader (SqlDataReader): fast, forward-only, read-only access. Methods: Read(), Close(), GetString(), GetInt32().
  • DataAdapter (SqlDataAdapter): bridge between database and DataSet. Methods: Fill(), Update().
  • DataSet/DataTable: in-memory, disconnected copy of data. Methods: Tables.Add(), AcceptChanges(), Clear().

Program

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string cs = "Data Source=.;Initial Catalog=CompanyDB;Integrated Security=True";

        using (SqlConnection con = new SqlConnection(cs))
        {
            con.Open();

            string[] names = { "Ram", "Sita", "Hari", "Gita", "Shyam" };
            string[] depts = { "IT", "HR", "Finance", "IT", "Sales" };
            decimal[] sal = { 50000, 40000, 65000, 30000, 45000 };

            for (int i = 0; i < 5; i++)
            {
                SqlCommand ins = new SqlCommand(
                    "INSERT INTO Employee (Eid, Name, Department, Salary) VALUES (@id,@n,@d,@s)", con);
                ins.Parameters.AddWithValue("@id", i + 1);
                ins.Parameters.AddWithValue("@n", names[i]);
                ins.Parameters.AddWithValue("@d", depts[i]);
                ins.Parameters.AddWithValue("@s", sal[i]);
                ins.ExecuteNonQuery();
            }
            Console.WriteLine("5 records inserted.");

            string q = "SELECT * FROM Employee WHERE Salary = (SELECT MAX(Salary) FROM Employee) " +
                       "OR Salary = (SELECT MIN(Salary) FROM Employee)";
            SqlCommand cmd = new SqlCommand(q, con);
            using (SqlDataReader r = cmd.ExecuteReader())
            {
                Console.WriteLine("Highest and lowest salary employees:");
                while (r.Read())
                    Console.WriteLine($"{r["Eid"]}  {r["Name"]}  {r["Department"]}  Rs {r["Salary"]}");
            }
        }
    }
}

With the sample data it displays Hari (Rs 65000, highest) and Gita (Rs 30000, lowest).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 2+8 marks

What is validation control in web development? Explain various control for validation in ASP.NET with suitable program

Answer

Validation control

A validation control is an ASP.NET server control that checks user input in a web form before it is processed, showing an error message if the data is invalid. It works on the client side (JavaScript) and is re-checked on the server. It improves data quality and security. The page-level check is Page.IsValid.

Validation controls in ASP.NET

  1. RequiredFieldValidator: ensures a field is not empty.
  2. CompareValidator: compares a value with another control or a constant (e.g. password confirmation, data type check).
  3. RangeValidator: checks that the value lies within a range (e.g. age 18 to 60).
  4. RegularExpressionValidator: matches a pattern (e.g. email, phone number).
  5. CustomValidator: user-defined client/server validation logic.
  6. ValidationSummary: displays all error messages together.

Program

<form id="form1" runat="server">
  Name:
  <asp:TextBox ID="txtName" runat="server" />
  <asp:RequiredFieldValidator ID="rfvName" runat="server"
      ControlToValidate="txtName" ErrorMessage="Name is required" ForeColor="Red" />
  <br />
  Age:
  <asp:TextBox ID="txtAge" runat="server" />
  <asp:RangeValidator ID="rvAge" runat="server" ControlToValidate="txtAge"
      MinimumValue="18" MaximumValue="60" Type="Integer"
      ErrorMessage="Age must be 18 to 60" ForeColor="Red" />
  <br />
  Password:
  <asp:TextBox ID="txtPass" runat="server" TextMode="Password" /><br />
  Confirm:
  <asp:TextBox ID="txtConfirm" runat="server" TextMode="Password" />
  <asp:CompareValidator ID="cvPass" runat="server" ControlToValidate="txtConfirm"
      ControlToCompare="txtPass" ErrorMessage="Passwords do not match" ForeColor="Red" />
  <br />
  Email:
  <asp:TextBox ID="txtEmail" runat="server" />
  <asp:RegularExpressionValidator ID="revEmail" runat="server"
      ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
      ErrorMessage="Invalid email" ForeColor="Red" />
  <br />
  <asp:ValidationSummary ID="vs" runat="server" ForeColor="Red" />
  <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
  <asp:Label ID="lblMsg" runat="server" />
</form>

Code-behind:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
        lblMsg.Text = "Form submitted successfully.";
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from TU BCA 2020 Fifth Semester Computer Networking (TU board exam, 2020), TU BCA 2021 Fifth Semester Computer Networking (TU board exam, 2021), TU BCA 2022 Fifth Semester Computer Networking (TU board exam, 2022), TU BCA 2023 Fifth Semester Computer Networking (TU board exam, 2023), TU BCA 2024 Fifth Semester Computer Networking (TU board exam, 2024), TU BCA 2025 Fifth Semester Computer Networking (TU board exam, 2025), TU BCA 2020 Fifth Semester Computer Graphics and Animation (TU board exam, 2020), TU BCA 2021 Fifth Semester Computer Graphics and Animation (TU board exam, 2021), TU BCA 2022 Fifth Semester Computer Graphics and Animation (TU board exam, 2022), TU BCA 2023 Fifth Semester Computer Graphics and Animation (TU board exam, 2023), TU BCA 2024 Fifth Semester Computer Graphics and Animation (TU board exam, 2024), TU BCA 2025 Fifth Semester Computer Graphics and Animation (TU board exam, 2025), TU BCA 2020 Fifth Semester .NET Technology (TU board exam, 2020), TU BCA 2021 Fifth Semester .NET Technology (TU board exam, 2021), TU BCA 2022 Fifth Semester .NET Technology (TU board exam, 2022), TU BCA 2023 Fifth Semester .NET Technology (TU board exam, 2023), TU BCA 2024 Fifth Semester .NET Technology (TU board exam, 2024), TU BCA 2025 Fifth Semester .NET Technology (TU board exam, 2025), TU BCA 2020 Fifth Semester Introduction to Management (TU board exam, 2020), TU BCA 2021 Fifth Semester Introduction to Management (TU board exam, 2021), TU BCA 2022 Fifth Semester Introduction to Management (TU board exam, 2022), TU BCA 2023 Fifth Semester Introduction to Management (TU board exam, 2023), TU BCA 2024 Fifth Semester Introduction to Management (TU board exam, 2024), TU BCA 2025 Fifth Semester Introduction to Management (TU board exam, 2025), TU BCA 2020 Fifth Semester MIS and E-Business (TU board exam, 2020), TU BCA 2021 Fifth Semester MIS and E-Business (TU board exam, 2021), TU BCA 2022 Fifth Semester MIS and E-Business (TU board exam, 2022), TU BCA 2023 Fifth Semester MIS and E-Business (TU board exam, 2023), TU BCA 2024 Fifth Semester MIS and E-Business (TU board exam, 2024) and TU BCA 2025 Fifth Semester MIS and E-Business (TU board exam, 2025). Answers are written for this site; check them against your class notes.