Unit 2: C# Programming Fundamentals - Subjective Questions
CSE253 — .Net Programming • Practice Questions with Detailed Answers
20 questions
Explain the concept of variables and data types in C#. Describe the commonly used value types and reference types with suitable examples.
Variables are named memory locations used to store data during program execution. Every variable in C# must have a declared data type.
Common value types:
int: Stores whole numbers, such asint age = 20;.float: Stores single-precision decimal values.double: Stores double-precision decimal values.decimal: Used for high-precision financial calculations.char: Stores a single Unicode character.bool: Storestrueorfalsevalues.structandenum: User-defined value types.
Common reference types:
string: Stores a sequence of characters.object: The base type of all C# types.- Arrays: Store multiple values of the same type.
- Classes, interfaces, and delegates.
Value-type variables directly contain their data, whereas reference-type variables store a reference to an object in memory. C# is strongly typed, so a variable normally cannot store a value of an incompatible type without conversion.
Describe input and output operations in C#. Explain the use of Console.ReadLine(), Console.Write(), Console.WriteLine(), and type conversion methods.
C# console applications use the Console class for standard input and output operations.
Console.Write(): Displays output without moving the cursor to the next line.Console.WriteLine(): Displays output and moves the cursor to the next line.Console.ReadLine(): Reads a complete line of input as a string.Console.ReadKey(): Reads a single key press.
Since Console.ReadLine() returns a string, numeric input must be converted before arithmetic operations. Common conversion methods include:
int.Parse(value)double.Parse(value)Convert.ToInt32(value)int.TryParse(value, out number)
TryParse() is safer because it returns false instead of throwing an exception when the input is invalid. For example, a program can read a user's age as text and convert it to an integer before using it in calculations.
Explain the structure and execution flow of a C# Hello World program.
A basic C# Hello World program demonstrates the essential structure of a console application.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}Explanation:
using System;imports the namespace containing theConsoleclass.class Programdeclares a class namedProgram.static void Main()is the entry point of the application.Console.WriteLine()displays text on the console.- Braces define blocks of code, and semicolons terminate statements.
When the program runs, the .NET runtime locates the Main() method, executes its statements, and displays Hello, World! as output. Modern C# versions may also support top-level statements, but the underlying execution still begins from the program entry point.
Describe conditional statements in C#. Compare if, if-else, nested if, and switch statements with suitable examples.
Conditional statements allow a program to select different actions based on Boolean conditions.
ifstatement: Executes a block only when a condition is true.if-elsestatement: Selects one of two alternatives.- Nested
if: Places one conditional statement inside another to test multiple levels of conditions. else-ifladder: Tests several conditions in sequence.switchstatement: Selects a block based on the value of an expression.
Example:
int marks = 75;
if (marks >= 50)
Console.WriteLine("Pass");
else
Console.WriteLine("Fail");A switch statement is useful when comparing one expression with several fixed values:
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
default:
Console.WriteLine("Other day");
break;
}if statements are suitable for ranges and complex conditions, while switch is often clearer for multiple fixed choices.
Explain the different types of loops in C#. Discuss for, while, do-while, and foreach loops, including their appropriate uses.
Loops repeatedly execute a block of code while a condition remains satisfied.
forloop: Used when the number of iterations is known or controlled by a counter.
for (int i = 0; i < 5; i++)
Console.WriteLine(i);whileloop: Tests the condition before each iteration. It may execute zero times.
while (condition)
{
// statements
}do-whileloop: Tests the condition after the loop body, so it executes at least once.
do
{
// statements
} while (condition);foreachloop: Iterates through every element of an array or collection without explicitly managing an index.
foreach (string name in names)
Console.WriteLine(name);The choice of loop depends on whether the iteration count is known, whether the body must execute at least once, and whether the program is traversing a collection.
What are jump statements in C#? Explain the use of break, continue, goto, return, and throw.
Jump statements change the normal sequential flow of program execution.
break: Immediately terminates the nearest loop orswitchstatement.continue: Skips the remaining statements in the current loop iteration and begins the next iteration.goto: Transfers control to a labeled statement. It should be used sparingly because excessive use can reduce readability.return: Exits a method and optionally sends a value back to the caller.throw: Generates an exception so that it can be handled by an appropriate exception handler.
For example, break can stop a search after finding a matching item, while continue can skip invalid values. A method such as int Add(int a, int b) uses return a + b; to provide a result. throw is commonly used when an argument or program state is invalid.
Explain one-dimensional and multidimensional arrays in C#. Describe array declaration, initialization, traversal, and common properties.
An array is a fixed-size collection of elements of the same data type. Array indexing starts at zero.
One-dimensional array:
int[] marks = { 70, 85, 90 };The array can also be declared and initialized separately:
int[] numbers = new int[5];Multidimensional array:
int[,] matrix =
{
{ 1, 2 },
{ 3, 4 }
};Arrays can be traversed using a for loop or a foreach loop. Important properties and methods include:
Length: Returns the total number of elements.Rank: Returns the number of dimensions.GetLength(dimension): Returns the size of a specific dimension.Sort(): Arranges elements in ascending order.Reverse(): Reverses the order of elements.
Arrays provide efficient indexed access, but their size normally cannot be changed after creation.
Explain strings in C#. Discuss string immutability and describe important string methods with examples.
A string in C# represents an immutable sequence of Unicode characters. Immutability means that once a string object is created, its contents cannot be changed. Operations that appear to modify a string actually create a new string.
Important string methods and properties include:
Length: Returns the number of characters.ToUpper()andToLower(): Change letter casing in the returned string.Trim(): Removes leading and trailing white space.Substring(): Extracts part of a string.Contains(): Checks whether a sequence exists.StartsWith()andEndsWith(): Test beginning and ending text.Replace(): Returns a string with matching text replaced.Split(): Divides a string into an array.IndexOf(): Finds the position of a character or substring.Equals(): Compares string contents.
For repeated string modifications, StringBuilder is generally more efficient because it provides a mutable character sequence.
Compare arrays and collections in C#. Explain the characteristics and uses of List<T>, Dictionary<TKey, TValue>, Queue<T>, and Stack<T>.
Arrays have a fixed size and provide fast indexed access. Collections are more flexible and often provide operations for adding, removing, searching, and organizing data.
List<T>: A dynamically sized, ordered collection. It supports indexing,Add(),Remove(), andContains().Dictionary<TKey, TValue>: Stores key-value pairs. Keys must be unique and provide efficient lookup.Queue<T>: Follows the FIFO principle, meaning the first item added is the first item removed. It usesEnqueue()andDequeue().Stack<T>: Follows the LIFO principle, meaning the last item added is the first item removed. It usesPush()andPop().
The generic form T provides compile-time type safety. Collections should be selected according to the required access pattern: indexed access for lists, key-based access for dictionaries, first-in-first-out processing for queues, and last-in-first-out processing for stacks.
Explain methods in C#. Discuss method declaration, return types, parameters, method overloading, and the difference between value and reference parameter passing.
A method is a named block of code that performs a specific task. It improves modularity, reuse, readability, and testing.
A method declaration generally contains an access modifier, return type, method name, parameter list, and body:
public int Add(int first, int second)
{
return first + second;
}Important concepts:
- The return type specifies the result, or
voidwhen no value is returned. - Parameters receive input values from the caller.
- Optional and named parameters can make calls more flexible.
- Method overloading allows methods with the same name but different parameter lists.
With value parameters, a copy of the argument is passed, so changing the parameter does not change the original variable. With reference parameters, the method can modify the caller's variable. C# supports ref, out, and in parameters. An out parameter must be assigned inside the method, while a ref argument must be initialized before the call.
Describe classes and objects in C#. Explain fields, properties, methods, and object creation with a suitable example.
A class is a blueprint that defines the data and behavior of an object. An object is an instance of a class created at runtime.
class Student
{
public string Name { get; set; }
public int Marks { get; set; }
public void Display()
{
Console.WriteLine($"{Name}: {Marks}");
}
}
Student student = new Student();
student.Name = "Asha";
student.Marks = 85;
student.Display();- Fields store data directly inside an object.
- Properties provide controlled access to data and may include getters and setters.
- Methods define operations or behavior.
- The
newkeyword creates an object and allocates memory for it.
Classes support abstraction and encapsulation by combining related data and operations into a single unit. Multiple objects created from the same class can hold different data while sharing the same structure and behavior.
What are constructors in C#? Explain default, parameterized, copy-style, and static constructors, and discuss constructor overloading.
A constructor is a special member of a class that initializes objects. It has the same name as the class and does not have a return type.
- Default constructor: Takes no parameters. If no constructor is declared, C# may provide an implicit parameterless constructor.
- Parameterized constructor: Accepts arguments to initialize object state.
- Copy-style constructor: Receives an object of the same class and copies selected values. C# does not create this automatically, but it can be defined by the programmer.
- Static constructor: Initializes static data and runs once before the first use of the type. It has no access modifier and takes no parameters.
Constructor overloading means defining multiple constructors with different parameter lists. It allows objects to be created in several valid ways. Constructors can also call another constructor in the same class using this(...), or a base-class constructor using base(...).
Explain access modifiers in C#. Compare public, private, protected, internal, protected internal, and private protected.
Access modifiers control where a class member or type can be accessed.
public: Accessible from any code that can access the containing type.private: Accessible only within the containing class or structure. It is the most restrictive normal member access level.protected: Accessible within the containing type and its derived classes.internal: Accessible anywhere within the same assembly.protected internal: Accessible from the same assembly or from derived classes in another assembly.private protected: Accessible within the containing type and derived classes located in the same assembly.
Access modifiers support information hiding and encapsulation. A class commonly keeps fields private and exposes controlled public properties or methods. This prevents uncontrolled modification and reduces dependencies between parts of a program.
Explain the four major object-oriented programming concepts in C#: encapsulation, abstraction, inheritance, and polymorphism.
The major object-oriented programming concepts are:
- Encapsulation: Combines data and related methods in a class and restricts direct access to internal state. Private fields with public properties are a common implementation.
- Abstraction: Shows only essential features while hiding implementation details. Abstract classes and interfaces are commonly used to define abstractions.
- Inheritance: Allows a derived class to reuse and extend members of a base class. It promotes code reuse and represents an "is-a" relationship.
- Polymorphism: Allows one interface or base type to represent objects of different derived types. It can occur through method overloading at compile time and method overriding at runtime.
Together, these concepts help create maintainable, extensible, and loosely coupled applications. Good object-oriented design also aims to assign responsibilities clearly and hide unnecessary implementation details.
Distinguish between method overloading and method overriding in C#. Explain how compile-time and runtime polymorphism are achieved.
Method overloading occurs when a class contains multiple methods with the same name but different parameter lists. The difference may be in the number, order, or types of parameters. The compiler selects the appropriate method, so overloading is a form of compile-time polymorphism.
void Print(int value) { }
void Print(string value) { }Method overriding occurs when a derived class provides a new implementation of a base-class method marked virtual, abstract, or already override.
class Animal
{
public virtual void Speak() { }
}
class Dog : Animal
{
public override void Speak() { }
}When a base-class reference refers to a Dog object, the overridden Dog.Speak() method is selected at runtime. Therefore, overriding provides runtime polymorphism, while overloading is resolved at compile time.
Explain exception handling in C#. Describe the roles of try, catch, finally, throw, and custom exceptions.
Exception handling manages abnormal conditions that occur during program execution, such as invalid input, division by zero, or a missing file.
try: Contains code that may generate an exception.catch: Handles an exception of a specified type.finally: Contains cleanup code that normally executes whether or not an exception occurs.throw: Explicitly raises an exception.
Example:
try
{
int result = numerator / denominator;
}
catch (DivideByZeroException)
{
Console.WriteLine("The denominator cannot be zero.");
}
finally
{
Console.WriteLine("Operation completed.");
}Specific exception types should be caught before general Exception types. A custom exception can be created by deriving a class from Exception. Exceptions should be handled only when the program can take a meaningful action; otherwise, they should be logged or propagated to a higher level.
Describe file handling in C#. Explain how to create, read, write, append, and close text files using the System.IO namespace.
File handling allows a program to store and retrieve data permanently. The System.IO namespace provides classes such as File, FileInfo, StreamReader, and StreamWriter.
Common operations include:
File.WriteAllText(path, content): Creates or overwrites a text file.File.AppendAllText(path, content): Adds content to the end of a file.File.ReadAllText(path): Reads the complete file as a string.File.ReadAllLines(path): Reads a file into an array of lines.File.Exists(path): Checks whether a file exists.
For larger or controlled operations, StreamReader and StreamWriter can be used. These objects should be disposed after use, preferably through a using statement:
using (StreamWriter writer = new StreamWriter("data.txt"))
{
writer.WriteLine("Sample data");
}File operations may throw exceptions such as FileNotFoundException, UnauthorizedAccessException, or IOException, so appropriate validation and exception handling are required.
Explain debugging fundamentals in C#. Discuss breakpoints, stepping commands, watches, the call stack, and common debugging practices.
Debugging is the systematic process of locating and correcting errors in a program.
- Breakpoint: Pauses execution at a selected line so variable values and program flow can be inspected.
- Step Over: Executes the current line without entering a called method.
- Step Into: Enters the called method to inspect its internal execution.
- Step Out: Completes the current method and returns to its caller.
- Watch window: Displays selected expressions or variables while execution is paused.
- Locals window: Shows variables available in the current scope.
- Call stack: Shows the sequence of method calls that led to the current execution point.
Effective debugging practices include reproducing the error consistently, reading exception messages and stack traces, inspecting values at boundaries, testing one assumption at a time, and using logging where interactive debugging is not possible. Compiler errors, runtime exceptions, and logical errors require different investigation strategies.
Design and explain a C# program that accepts marks for several subjects, calculates the average, assigns a grade using conditional statements, and displays the result.
The program should use input operations, type conversion, arrays or collections, loops, arithmetic, and conditional statements.
Console.Write("Enter the number of subjects: ");
int count = int.Parse(Console.ReadLine());
int total = 0;
for (int i = 0; i < count; i++)
{
Console.Write("Enter marks: ");
int mark = int.Parse(Console.ReadLine());
total += mark;
}
double average = (double)total / count;
string grade;
if (average >= 80)
grade = "A";
else if (average >= 60)
grade = "B";
else if (average >= 50)
grade = "C";
else
grade = "F";
Console.WriteLine($"Average: {average:F2}");
Console.WriteLine($"Grade: {grade}");The loop collects all marks and adds them to total. The explicit conversion to double preserves the fractional part of the average. The if-else-if ladder selects a grade based on the average. A complete solution should also validate that the subject count and marks are within acceptable ranges.
Compare value types and reference types in C# with respect to memory behavior, assignment, parameter passing, and examples.
Value types and reference types differ in how variables represent data.
Value types:
- Store the actual value directly.
- Common examples include
int,double,bool,char,struct, andenum. - Assignment copies the value, so changing one variable normally does not affect another.
- They are commonly stored on the stack or within an object, depending on context.
Reference types:
- Store a reference to an object containing the data.
- Examples include classes, arrays, delegates, and strings.
- Assignment copies the reference, so two variables may refer to the same object.
- Objects are managed by the garbage collector.
When a value type is passed by value, the method receives a copy. A reference-type variable passed by value also passes a copy, but that copy still refers to the same object. Therefore, the method can change the object's members, although it cannot replace the caller's reference unless ref is used.
Explain the concept of variables and data types in C#. Describe the commonly used value types and reference types with suitable examples.
Variables are named memory locations used to store data during program execution. Every variable in C# must have a declared data type.
Common value types:
int: Stores whole numbers, such asint age = 20;.float: Stores single-precision decimal values.double: Stores double-precision decimal values.decimal: Used for high-precision financial calculations.char: Stores a single Unicode character.bool: Storestrueorfalsevalues.structandenum: User-defined value types.
Common reference types:
string: Stores a sequence of characters.object: The base type of all C# types.- Arrays: Store multiple values of the same type.
- Classes, interfaces, and delegates.
Value-type variables directly contain their data, whereas reference-type variables store a reference to an object in memory. C# is strongly typed, so a variable normally cannot store a value of an incompatible type without conversion.
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 →