Unit 2: C# Programming Fundamentals - Subjective Questions
INT402 — Modern Web Programming Tools And Techniques • Practice Questions with Detailed Answers
20 questions
Define variables and data types in C#. Explain the major categories of C# data types with suitable examples.
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.
Write and explain a simple C# Hello World program. Describe the purpose of each major component.
A simple C# Hello World program is:
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 prints Hello, World!.
Explain the different types of operators available in C#. What is operator precedence and how can parentheses affect an expression?
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.
Describe the conditional statements supported by C#. Illustrate if, if-else, else-if ladder, and switch with examples.
Conditional statements select a block of code according to whether a condition is true or false.
1. if statement
Executes code only when its condition is true.
if (age >= 18)
{
Console.WriteLine("Eligible to vote");
}2. if-else statement
Selects one of two alternatives.
if (number % 2 == 0)
Console.WriteLine("Even");
else
Console.WriteLine("Odd");3. else-if ladder
Tests multiple conditions in sequence.
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. switch statement
Selects a block based on the value or pattern of an expression.
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}An if-else structure is suitable for ranges and complex Boolean conditions, whereas switch is often clearer when comparing one expression against several distinct cases.
Compare the for, while, and do-while loops in C#. Give their syntax, working, and suitable use cases.
Loops repeatedly execute a block of code while a condition is satisfied.
for loop
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.
while loop
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-while loop
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, for and while are entry-controlled loops, while do-while is an exit-controlled loop.
Explain the purpose of the break, continue, return, and goto jump statements in C#. Provide an example of each.
Jump statements transfer program control from one location to another.
break
Terminates the nearest loop or switch statement.
for (int i = 1; i <= 10; i++)
{
if (i == 5)
break;
Console.WriteLine(i);
}This prints 1 to 4.
continue
Skips the remaining statements in the current loop iteration.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue;
Console.WriteLine(i);
}This skips 3.
return
Terminates a method and optionally returns a value.
static int Square(int number)
{
return number * number;
}goto
Transfers control to a labeled statement.
int number = 1;
start:
Console.WriteLine(number);
number++;
if (number <= 3)
goto start;Although goto is supported, excessive use should be avoided because it can make program flow difficult to understand and maintain.
What is an array in C#? Explain one-dimensional, multidimensional, and jagged arrays with examples.
An array is a fixed-size collection of elements of the same data type. Array indexes begin at 0, and the Length property gives the total number of elements.
One-dimensional array
It stores elements in a linear sequence.
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.
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.
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.
Describe common techniques and methods used to manipulate arrays in C#. Explain traversal, searching, sorting, reversing, copying, and resizing.
Array manipulation includes accessing, modifying, arranging, and copying elements.
Traversal
int[] values = { 30, 10, 20 };
foreach (int value in values)
{
Console.WriteLine(value);
}Searching
Array.IndexOf returns the index of an element or -1 when it is not found.
int index = Array.IndexOf(values, 10);Sorting
Array.Sort(values);After sorting, the array contains 10, 20, 30.
Reversing
Array.Reverse(values);Copying
int[] copy = new int[values.Length];
Array.Copy(values, copy, values.Length);Resizing
Array.Resize(ref values, 5);Arrays normally have a fixed size. Array.Resize creates a new array, copies the available elements, and updates the reference. If frequent insertion and deletion are required, a dynamic collection such as List<T> is generally more suitable.
Explain the string type in C# and discuss any five commonly used string methods or properties with examples.
A C# string is a sequence of Unicode characters represented by the System.String class. 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.
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.Equals with an appropriate StringComparison option when case or culture rules matter.
How are strings manipulated in C#? Compare string concatenation, interpolation, Split, Join, and StringBuilder.
Strings can be manipulated in several ways depending on the operation and performance requirements.
Concatenation
The + operator combines strings.
string fullName = firstName + " " + lastName;String interpolation
Interpolation provides readable formatted strings.
string message = $"Name: {fullName}, Age: {age}";Splitting
Split divides a string into an array.
string data = "red,green,blue";
string[] colors = data.Split(',');Joining
Join combines multiple strings using a separator.
string result = string.Join(" | ", colors);StringBuilder
StringBuilder, available in System.Text, efficiently performs repeated modifications.
using System.Text;
StringBuilder builder = new StringBuilder();
builder.Append("Modern");
builder.Append(" Web");
builder.AppendLine(" Programming");
string finalText = builder.ToString();Because string is immutable, repeated concatenation in a large loop can create many temporary objects. StringBuilder maintains a mutable character buffer and is therefore preferable for numerous additions, insertions, removals, or replacements.
Define object-oriented programming. Explain its principal concepts and state the advantages of using OOP in C#.
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.
Explain classes and objects in C#. Write a class containing fields, properties, and methods, and demonstrate object creation.
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.
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:
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.
Distinguish between encapsulation and abstraction in C#. How are access modifiers, properties, abstract classes, and interfaces related to these concepts?
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.
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.
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.
What is a constructor in C#? Explain default, parameterized, copy-style, static, and private constructors, including constructor overloading and chaining.
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
public Product()
{
Name = "Unknown";
Price = 0;
}If a class declares no instance constructor, C# normally supplies an implicit parameterless constructor.
Parameterized constructor
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.
public Product(Product other)
{
Name = other.Name;
Price = other.Price;
}Static constructor
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
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:
public Product(string name) : this(name, 0)
{
}A derived constructor can call a base-class constructor using base(...).
Explain inheritance in C#. Discuss base and derived classes, types of inheritance supported by C#, member accessibility, and the use of the base keyword.
Inheritance allows a derived class to acquire and extend accessible members of a base class.
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.
What is polymorphism? Compare compile-time polymorphism and runtime polymorphism in C# with examples of method overloading and method overriding.
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.
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 virtual and override.
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal sound");
}
}
class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}Usage:
Animal animal = new Dog();
animal.Speak();The output is Dog barks because 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.
Explain abstract classes and abstract methods in C#. How does an abstract class differ from a concrete class and an interface?
An abstract class is an incomplete base class declared with the abstract keyword. It cannot be instantiated directly and is intended to be inherited.
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.
Describe exception handling in C#. Explain try, catch, finally, throw, multiple catch blocks, and custom exceptions.
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.
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.
if (age < 0)
throw new ArgumentOutOfRangeException(nameof(age));Multiple catch blocks should be ordered from more specific exception types to more general types.
A custom exception can inherit from Exception:
class InvalidBalanceException : Exception
{
public InvalidBalanceException(string message) : base(message)
{
}
}Exceptions should represent exceptional conditions and should not replace ordinary conditional logic.
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.
A possible solution is:
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.
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.
The system can define an abstract Employee class and specialized employee types.
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:
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.
Define variables and data types in C#. Explain the major categories of C# data types with suitable examples.
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.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. 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. Chip in only if it was worth it. What it pays for →