Unit 2 subjective questions C# Programming Fundamentals
INT402 — Modern Web Programming Tools And Techniques 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define variables and data types in C#. Explain the major categories of C# data types with suitable examples.
Model answer
Variable: A variable is a named memory location used to store a value that may change during program execution. It must be declared with a data type before it is used.
Syntax:
dataType variableName = value;Example:
int age = 20;Major categories of C# data types
-
Value types: Store their actual values directly.
- Integer types:
byte,short,int,long - Floating-point types:
float,double - Decimal type:
decimal - Other types:
char,bool,struct,enum
- Integer types:
-
Reference types: Store a reference to the memory location containing the object.
string- Arrays
- Classes
- Interfaces
- Delegates
-
Pointer types: Store memory addresses and are mainly used in unsafe code.
Examples:
int count = 10;double price = 45.75;char grade = 'A';bool isValid = true;string name = "Ravi";
The selected data type determines the range of values, memory requirements, and operations permitted on a variable.
-
-
Question 2 of 20
Write and explain a simple C# Hello World program. Describe the purpose of each major component.
Model answer
A simple C# Hello World program is:
C#using System; class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); } }Explanation
using System;imports theSystemnamespace, which contains commonly used classes such asConsole.class Programdeclares a class namedProgram. C# program statements are normally organized inside classes.static void Main(string[] args)is the entry point of the application.staticallows the method to run without creating aProgramobject.voidindicates that the method does not return a value.string[] argsstores command-line arguments.
Console.WriteLine(...)displays text on the console and moves the cursor to the next line.- Semicolon
;terminates a C# statement. - Braces
{ }define the boundaries of classes and methods.
When the application starts, the runtime invokes
Main, which printsHello, World!. -
Question 3 of 20
Explain the different types of operators available in C#. What is operator precedence and how can parentheses affect an expression?
Model answer
C# provides several categories of operators:
- Arithmetic operators:
+,-,*,/,% - Relational operators:
==,!=,<,>,<=,>= - Logical operators:
&&,||,! - Assignment operators:
=,+=,-=,*=,/=,%= - Increment and decrement operators:
++,-- - Bitwise operators:
&,|,^,~,<<,>> - Conditional operator:
condition ? value1 : value2 - Null-related operators:
??,?.
Operator precedence determines which operation is performed first when an expression contains multiple operators. For example:
int result = 10 + 2 * 3;Multiplication has higher precedence than addition, so the expression is evaluated as:
Parentheses can explicitly change the order:
int result = (10 + 2) * 3;Now the result is:
When operators have the same precedence, associativity determines their evaluation order. Parentheses should be used to improve clarity and avoid unintended results.
- Arithmetic operators:
-
Question 4 of 20
Describe the conditional statements supported by C#. Illustrate
if,if-else,else-ifladder, andswitchwith examples.Model answer
Conditional statements select a block of code according to whether a condition is true or false.
1.
ifstatementExecutes code only when its condition is true.
C#if (age >= 18) { Console.WriteLine("Eligible to vote"); }2.
if-elsestatementSelects one of two alternatives.
C#if (number % 2 == 0) Console.WriteLine("Even"); else Console.WriteLine("Odd");3.
else-ifladderTests multiple conditions in sequence.
C#if (marks >= 80) Console.WriteLine("Grade A"); else if (marks >= 60) Console.WriteLine("Grade B"); else if (marks >= 40) Console.WriteLine("Grade C"); else Console.WriteLine("Fail");4.
switchstatementSelects a block based on the value or pattern of an expression.
C#switch (day) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; default: Console.WriteLine("Invalid day"); break; }An
if-elsestructure is suitable for ranges and complex Boolean conditions, whereasswitchis often clearer when comparing one expression against several distinct cases. -
Question 5 of 20
Compare the
for,while, anddo-whileloops in C#. Give their syntax, working, and suitable use cases.Model answer
Loops repeatedly execute a block of code while a condition is satisfied.
forloopC#for (int i = 1; i <= 5; i++) { Console.WriteLine(i); }- Initialization, condition, and update are written together.
- It is suitable when the number of iterations is known.
- The condition is checked before every iteration.
whileloopC#int i = 1; while (i <= 5) { Console.WriteLine(i); i++; }- It is suitable when the number of iterations is not known in advance.
- The condition is checked before the body executes.
- The body may execute zero times.
do-whileloopC#int i = 1; do { Console.WriteLine(i); i++; } while (i <= 5);- The condition is checked after the loop body.
- The body is executed at least once.
- It is useful for menu-driven programs and input validation.
Thus,
forandwhileare entry-controlled loops, whiledo-whileis an exit-controlled loop. -
-
Question 6 of 20
Explain the purpose of the
break,continue,return, andgotojump statements in C#. Provide an example of each.Model answer
Jump statements transfer program control from one location to another.
breakTerminates the nearest loop or
switchstatement.C#for (int i = 1; i <= 10; i++) { if (i == 5) break; Console.WriteLine(i); }This prints
1to4.continueSkips the remaining statements in the current loop iteration.
C#for (int i = 1; i <= 5; i++) { if (i == 3) continue; Console.WriteLine(i); }This skips
3.returnTerminates a method and optionally returns a value.
C#static int Square(int number) { return number * number; }gotoTransfers control to a labeled statement.
C#int number = 1; start: Console.WriteLine(number); number++; if (number <= 3) goto start;Although
gotois supported, excessive use should be avoided because it can make program flow difficult to understand and maintain. -
Question 7 of 20
What is an array in C#? Explain one-dimensional, multidimensional, and jagged arrays with examples.
Model answer
An array is a fixed-size collection of elements of the same data type. Array indexes begin at
0, and theLengthproperty gives the total number of elements.One-dimensional array
It stores elements in a linear sequence.
C#int[] numbers = { 10, 20, 30, 40 }; Console.WriteLine(numbers[1]);The output is
20.Multidimensional array
It has two or more dimensions and is usually rectangular.
C#int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } }; Console.WriteLine(matrix[1, 2]);The output is
6.Jagged array
It is an array whose elements are themselves arrays. Its rows may have different lengths.
C#int[][] values = new int[3][]; values[0] = new int[] { 1, 2 }; values[1] = new int[] { 3, 4, 5 }; values[2] = new int[] { 6 };A multidimensional array has a uniform rectangular structure, while a jagged array can represent irregular data and stores each inner array separately.
-
Question 8 of 20
Describe common techniques and methods used to manipulate arrays in C#. Explain traversal, searching, sorting, reversing, copying, and resizing.
Model answer
Array manipulation includes accessing, modifying, arranging, and copying elements.
Traversal
C#int[] values = { 30, 10, 20 }; foreach (int value in values) { Console.WriteLine(value); }Searching
Array.IndexOfreturns the index of an element or-1when it is not found.C#int index = Array.IndexOf(values, 10);Sorting
C#Array.Sort(values);After sorting, the array contains
10, 20, 30.Reversing
C#Array.Reverse(values);Copying
C#int[] copy = new int[values.Length]; Array.Copy(values, copy, values.Length);Resizing
C#Array.Resize(ref values, 5);Arrays normally have a fixed size.
Array.Resizecreates a new array, copies the available elements, and updates the reference. If frequent insertion and deletion are required, a dynamic collection such asList<T>is generally more suitable. -
Question 9 of 20
Explain the
stringtype in C# and discuss any five commonly used string methods or properties with examples.Model answer
A C#
stringis a sequence of Unicode characters represented by theSystem.Stringclass. Strings are immutable, meaning that their contents cannot be changed after they are created. An operation that appears to modify a string actually produces a new string.C#string text = " Modern Web Programming ";Common members
-
Lengthreturns the number of characters.int size = text.Length;
-
Trim()removes leading and trailing whitespace.string clean = text.Trim();
-
ToUpper()converts characters to uppercase.string upper = clean.ToUpper();
-
Contains()checks whether a substring is present.bool found = clean.Contains("Web");
-
Replace()replaces matching text.string changed = clean.Replace("Web", "Internet");
-
Substring()extracts part of a string.string part = clean.Substring(0, 6);
-
IndexOf()returns the position of a character or substring.int position = clean.IndexOf("Web");
String comparisons should use methods such as
string.Equalswith an appropriateStringComparisonoption when case or culture rules matter. -
-
Question 10 of 20
How are strings manipulated in C#? Compare string concatenation, interpolation,
Split,Join, andStringBuilder.Model answer
Strings can be manipulated in several ways depending on the operation and performance requirements.
Concatenation
The
+operator combines strings.C#string fullName = firstName + " " + lastName;String interpolation
Interpolation provides readable formatted strings.
C#string message = $"Name: {fullName}, Age: {age}";Splitting
Splitdivides a string into an array.C#string data = "red,green,blue"; string[] colors = data.Split(',');Joining
Joincombines multiple strings using a separator.C#string result = string.Join(" | ", colors);StringBuilderStringBuilder, available inSystem.Text, efficiently performs repeated modifications.C#using System.Text; StringBuilder builder = new StringBuilder(); builder.Append("Modern"); builder.Append(" Web"); builder.AppendLine(" Programming"); string finalText = builder.ToString();Because
stringis immutable, repeated concatenation in a large loop can create many temporary objects.StringBuildermaintains a mutable character buffer and is therefore preferable for numerous additions, insertions, removals, or replacements. -
Question 11 of 20
Define object-oriented programming. Explain its principal concepts and state the advantages of using OOP in C#.
Model answer
Object-oriented programming (OOP) is a programming approach in which software is organized around objects containing data and behavior.
Principal concepts
- Class: A blueprint that declares the data and operations of a type.
- Object: A runtime instance of a class.
- Encapsulation: Bundling data and methods together and restricting direct access to implementation details.
- Abstraction: Presenting essential features while hiding unnecessary complexity.
- Inheritance: Creating a new class from an existing class to reuse or extend behavior.
- Polymorphism: Allowing the same method or interface to produce different behavior for different objects.
Advantages
- Modularity: A program can be divided into independent classes.
- Reusability: Existing classes can be reused through composition or inheritance.
- Maintainability: Changes can be localized to particular classes.
- Security: Access modifiers protect internal data.
- Extensibility: New classes and features can be added with limited impact on existing code.
- Real-world modeling: Related data and operations can be represented as meaningful objects.
C# supports OOP through classes, objects, interfaces, properties, constructors, inheritance, virtual methods, and abstract classes.
-
Question 12 of 20
Explain classes and objects in C#. Write a class containing fields, properties, and methods, and demonstrate object creation.
Model answer
A class is a user-defined type that acts as a blueprint for objects. An object is an instance of that class created in memory.
C#using System; class Student { private int marks; public string Name { get; set; } public int Marks { get { return marks; } set { if (value >= 0 && value <= 100) marks = value; } } public void Display() { Console.WriteLine($"Name: {Name}, Marks: {Marks}"); } }Object creation and use:
C#Student student1 = new Student(); student1.Name = "Anita"; student1.Marks = 85; student1.Display();Components
- Field:
marksstores the internal state. - Properties:
NameandMarksprovide controlled access to data. - Method:
Displaydefines object behavior. - Reference variable:
student1refers to the created object. newoperator: Creates and initializes an object.
Multiple objects of the same class have separate instance data but share the class's method definitions.
- Field:
-
Question 13 of 20
Distinguish between encapsulation and abstraction in C#. How are access modifiers, properties, abstract classes, and interfaces related to these concepts?
Model answer
Encapsulation and abstraction both hide details, but they serve different purposes.
Encapsulation
- Bundles data and operations inside a class.
- Protects an object's state from uncontrolled access.
- Focuses on how access to data is controlled.
- Implemented using classes, access modifiers, fields, properties, and methods.
C#class BankAccount { private decimal balance; public decimal Balance { get { return balance; } } public void Deposit(decimal amount) { if (amount > 0) balance += amount; } }The private field cannot be modified directly from outside the class.
Abstraction
- Exposes essential behavior while hiding implementation details.
- Focuses on what an object does rather than how it does it.
- Commonly implemented using abstract classes and interfaces.
C#abstract class Shape { public abstract double Area(); }Role of access modifiers
public: Accessible from anywhere.private: Accessible only within the containing type.protected: Accessible in the containing type and derived classes.internal: Accessible within the same assembly.
Thus, encapsulation protects implementation and state, while abstraction provides a simplified contract for using functionality.
-
Question 14 of 20
What is a constructor in C#? Explain default, parameterized, copy-style, static, and private constructors, including constructor overloading and chaining.
Model answer
A constructor is a special class member that initializes an object. It has the same name as the class and has no return type.
Parameterless or default-style constructor
C#public Product() { Name = "Unknown"; Price = 0; }If a class declares no instance constructor, C# normally supplies an implicit parameterless constructor.
Parameterized constructor
C#public Product(string name, decimal price) { Name = name; Price = price; }Copy-style constructor
C# does not automatically define a special copy constructor, but one can be written manually.
C#public Product(Product other) { Name = other.Name; Price = other.Price; }Static constructor
C#static Product() { Category = "General"; }It initializes static data, has no parameters or access modifier, and runs automatically once before the type is first used.
Private constructor
C#private Product() { }It prevents normal object creation from outside the class and is useful in factory or singleton designs.
Constructor overloading and chaining
A class can declare multiple constructors with different parameter lists. One constructor can call another using
this:C#public Product(string name) : this(name, 0) { }A derived constructor can call a base-class constructor using
base(...). -
Question 15 of 20
Explain inheritance in C#. Discuss base and derived classes, types of inheritance supported by C#, member accessibility, and the use of the
basekeyword.Model answer
Inheritance allows a derived class to acquire and extend accessible members of a base class.
C#class Employee { protected string name; public Employee(string name) { this.name = name; } public void DisplayName() { Console.WriteLine(name); } } class Manager : Employee { public Manager(string name) : base(name) { } public void ConductMeeting() { Console.WriteLine($"{name} is conducting a meeting"); } }Important points
Employeeis the base class.Manageris the derived class.:specifies inheritance.protectedmembers are available inside the base class and its derived classes.base(name)invokes the base-class constructor.base.MemberNamecan access an accessible base-class member hidden or overridden in a derived class.- Constructors and private members are not inherited as directly accessible members.
Types of inheritance
C# class inheritance directly supports:
- Single inheritance
- Multilevel inheritance
- Hierarchical inheritance
C# does not support multiple inheritance of classes, but a class can implement multiple interfaces. This avoids many ambiguities associated with inheriting implementation from multiple classes.
-
Question 16 of 20
What is polymorphism? Compare compile-time polymorphism and runtime polymorphism in C# with examples of method overloading and method overriding.
Model answer
Polymorphism means one interface or method name can represent different forms of behavior.
Compile-time polymorphism
It is usually achieved through method overloading. The compiler selects the method according to the argument list.
C#class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } }The methods have the same name but different parameter types.
Runtime polymorphism
It is achieved through method overriding using
virtualandoverride.C#class Animal { public virtual void Speak() { Console.WriteLine("Animal sound"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Dog barks"); } }Usage:
C#Animal animal = new Dog(); animal.Speak();The output is
Dog barksbecause the runtime selects the method associated with the actual object.Difference
- Overloading is resolved at compile time and generally changes the parameter list.
- Overriding is resolved at runtime and requires inheritance.
- An overridden method keeps a compatible signature and return type.
- Runtime polymorphism makes software extensible because client code can work with base-class or interface references.
-
Question 17 of 20
Explain abstract classes and abstract methods in C#. How does an abstract class differ from a concrete class and an interface?
Model answer
An abstract class is an incomplete base class declared with the
abstractkeyword. It cannot be instantiated directly and is intended to be inherited.C#abstract class Shape { public string Color { get; set; } public abstract double CalculateArea(); public void DisplayColor() { Console.WriteLine(Color); } } class Circle : Shape { public double Radius { get; set; } public override double CalculateArea() { return Math.PI * Radius * Radius; } }Abstract methods
- Have no body in the abstract class.
- Must be implemented by a non-abstract derived class.
- Are implicitly virtual but use
abstractrather thanvirtual.
Comparison
- A concrete class can be instantiated and must provide implementations for all inherited abstract members.
- An abstract class may contain fields, constructors, properties, concrete methods, virtual methods, and abstract methods.
- An interface primarily defines a contract that multiple unrelated classes can implement.
- A class can inherit from only one class, whether abstract or concrete, but can implement multiple interfaces.
- An abstract class is appropriate when related classes share state or implementation; an interface is appropriate when types need to share a capability or contract.
-
Question 18 of 20
Describe exception handling in C#. Explain
try,catch,finally,throw, multiple catch blocks, and custom exceptions.Model answer
An exception is an object representing an abnormal condition that interrupts normal program execution. Exception handling allows a program to detect errors and respond gracefully.
C#try { int number = int.Parse(Console.ReadLine()); int result = 100 / number; Console.WriteLine(result); } catch (FormatException ex) { Console.WriteLine($"Invalid format: {ex.Message}"); } catch (DivideByZeroException ex) { Console.WriteLine($"Division error: {ex.Message}"); } finally { Console.WriteLine("Operation completed"); }Keywords
try: Contains statements that may generate an exception.catch: Handles a matching exception type.finally: Executes whether or not an exception occurs and is commonly used for cleanup.throw: Explicitly raises an exception.
C#if (age < 0) throw new ArgumentOutOfRangeException(nameof(age));Multiple
catchblocks should be ordered from more specific exception types to more general types.A custom exception can inherit from
Exception:C#class InvalidBalanceException : Exception { public InvalidBalanceException(string message) : base(message) { } }Exceptions should represent exceptional conditions and should not replace ordinary conditional logic.
-
Question 19 of 20
Develop a C# program that reads a collection of marks, validates the input, stores the values in an array, and displays the total, average, highest mark, and result category. Explain the concepts used.
Model answer
A possible solution is:
C#using System; class Program { static void Main() { int[] marks = new int[5]; int total = 0; for (int i = 0; i < marks.Length; i++) { while (true) { try { Console.Write($"Enter mark {i + 1}: "); int value = int.Parse(Console.ReadLine()); if (value < 0 || value > 100) throw new ArgumentOutOfRangeException(); marks[i] = value; break; } catch (FormatException) { Console.WriteLine("Enter a valid integer."); } catch (ArgumentOutOfRangeException) { Console.WriteLine("Mark must be from 0 to 100."); } } } int highest = marks[0]; foreach (int mark in marks) { total += mark; if (mark > highest) highest = mark; } double average = (double)total / marks.Length; string category; if (average >= 75) category = "Distinction"; else if (average >= 60) category = "First Class"; else if (average >= 40) category = "Pass"; else category = "Fail"; Console.WriteLine($"Total: {total}"); Console.WriteLine($"Average: {average:F2}"); Console.WriteLine($"Highest: {highest}"); Console.WriteLine($"Result: {category}"); } }Concepts used
- An array stores marks of the same type.
- A
forloop controls indexed input. - A
whileloop repeats until valid input is supplied. try-catchhandles formatting and range errors.breakexits the validation loop.- A
foreachloop calculates the total and highest mark. - Explicit casting prevents integer division.
- An
else-ifladder determines the result category.
-
Question 20 of 20
Design an object-oriented C# model for an employee payroll system using encapsulation, constructors, inheritance, polymorphism, an abstract class, arrays, string manipulation, and exception handling.
Model answer
The system can define an abstract
Employeeclass and specialized employee types.C#using System; abstract class Employee { private decimal basicPay; public string Name { get; } public decimal BasicPay { get { return basicPay; } protected set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); basicPay = value; } } protected Employee(string name, decimal basicPay) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Name is required."); Name = name.Trim(); BasicPay = basicPay; } public abstract decimal CalculateSalary(); public virtual string GetDetails() { return $"Employee: {Name}, Salary: {CalculateSalary():F2}"; } } class PermanentEmployee : Employee { public decimal Allowance { get; } public PermanentEmployee(string name, decimal basicPay, decimal allowance) : base(name, basicPay) { if (allowance < 0) throw new ArgumentOutOfRangeException(nameof(allowance)); Allowance = allowance; } public override decimal CalculateSalary() { return BasicPay + Allowance; } } class ContractEmployee : Employee { public ContractEmployee(string name, decimal contractAmount) : base(name, contractAmount) { } public override decimal CalculateSalary() { return BasicPay; } }Polymorphic processing can be performed through an array:
C#try { Employee[] employees = { new PermanentEmployee("Asha", 30000m, 5000m), new ContractEmployee("Vikram", 25000m) }; foreach (Employee employee in employees) { Console.WriteLine(employee.GetDetails()); } } catch (ArgumentException ex) { Console.WriteLine($"Payroll error: {ex.Message}"); }Application of concepts
- Encapsulation: Private
basicPayis controlled through a property. - Abstraction:
Employeedefines the essential payroll contract. - Constructors: Validate and initialize each object.
- Inheritance: Specialized classes derive from
Employee. - Polymorphism:
CalculateSalaryproduces behavior appropriate to the runtime object. - Arrays: An
Employee[]stores objects of different derived classes. - String manipulation:
Trim, interpolation, and formatting create output. - Exception handling: Invalid names and negative amounts are detected and handled.
- Encapsulation: Private
That's unit 2
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 2 of INT402 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 2 of INT402 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill; the rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks.