What is the importance of Garbage collection in .
NET
framework? Explain the .NET framework architecture with
suitable diagram
Garbage Collection (GC) is an automatic memory management feature in the
.NET Framework. It’s like a cleanup crew that frees up memory used by
objects in your C# program that are no longer needed, so you don’t have to
manually deallocate memory (unlike in languages like C++).
1. Prevents Memory Leaks:
o In Java or C#, when you create objects (e.g., a new Student()),
they take up memory. If you forget to free this memory, it leads
to memory leaks, making your program slow or crashing it. GC
automatically finds and removes unused objects, keeping your
program efficient.
o Example: Imagine you’re throwing a party and keep piling plates
(objects) on a table (memory). If you don’t clear old plates, you
run out of space. GC is like a waiter who clears unused plates for
you.
2. Saves Developer Time:
o You don’t need to write code to manually free memory (like free()
in C). This makes coding faster and reduces errors, especially for
beginners like you.
o Java Comparison: Java has a similar GC, so you’re already
familiar with not worrying about memory cleanup. C#’s GC works
similarly but is optimized for .NET.
3. Improves Program Stability:
o GC runs in the background, freeing memory at the right time
(e.g., when an object has no references). This ensures your
program doesn’t crash due to memory shortages.
o Example: In a Windows Form app, if you create many form
objects but stop using some, GC cleans them up so your app
doesn’t slow down.
4. Supports .NET’s Managed Environment:
o .NET’s Common Language Runtime (CLR) relies on GC to manage
memory for all .NET languages (C#, VB.NET, etc.). This makes
your code portable and safe across different .NET apps.
How Does GC Work (Simplified)?
GC tracks objects in memory (on the “heap”).
It identifies objects with no references (e.g., a variable no longer
pointing to an object).
It frees that memory and compacts the heap to avoid fragmentation.
Key Term: Generations (0, 1, 2) – GC organizes objects by age to
optimize cleanup. New objects are in Generation 0, and older ones
move to 1 or 2 if they survive cleanups.
Garbage Collection in .NET automatically manages memory by freeing
unused objects, preventing leaks, improving performance, and simplifying
coding in the CLR-managed environment.”
.NET Framework Architecture
What is the .NET Framework?
The .NET Framework is a platform by Microsoft for building apps (desktop,
web, etc.) using languages like C#. It provides tools, libraries, and a runtime
environment to make development easier and apps more reliable. Think of it
as a toolbox with everything you need to build and run a program.
Architecture Components (Simplified): The .NET Framework has layers
that work together. Here’s a breakdown for your exam:
1. Operating System:
o The base layer. .NET runs on Windows (your new OS!),
interacting with hardware via the OS.
2. Common Language Runtime (CLR):
o The heart of .NET, like an engine running your C# code.
o Key tasks:
Garbage Collection: Manages memory (as explained
above).
Just-In-Time Compilation (JIT): Converts C# code to
machine code at runtime.
Exception Handling: Manages errors (try-catch).
Security: Ensures code runs safely (e.g., prevents
unauthorized access).
o Java Comparison: CLR is like Java’s JVM (Java Virtual Machine).
3. Base Class Library (BCL):
o A huge library of pre-built code (like Java’s standard library).
o Provides classes for:
File handling (System.IO).
Database access (System.Data, e.g., ADO.NET).
UI for Windows Forms (System.Windows.Forms).
Networking, collections, etc.
o Example: Use Console.WriteLine from System namespace to
print output.
4. ASP.NET/Windows Forms/Other Libraries:
o Tools for specific apps:
Windows Forms: For desktop GUIs (e.g., a login form).
ASP.NET: For web apps.
ADO.NET: For database connections (e.g., SQL Server).
o For Exams: TU Nepal often focuses on Windows Forms and
ADO.NET for BCA.
5. Languages (C#, VB.NET, etc.):
o You write code in C#, which is compiled into Intermediate
Language (IL).
o CLR converts IL to machine code via JIT.
6. Applications:
o The final apps you build (e.g., a Windows Form app or a web
app).
Text-Based Diagram of .NET Framework Architecture:
Explanation of Diagram:
Bottom to Top: The OS supports the CLR, which runs your code. BCL
provides reusable code, and libraries like Windows Forms/ADO.NET help
build specific apps. Your C# program sits on top.
For Visualization: Imagine a cake. The OS is the plate, CLR is the
base layer, BCL is the frosting, libraries are decorations, and your app
is the cherry on top.
Key Exam Points:
CLR: Manages code execution, memory (via GC), and safety.
BCL: Provides ready-to-use classes for common tasks.
Libraries: Windows Forms for GUIs, ADO.NET for databases.
TU Focus: Expect questions on CLR’s role, GC, or simple Windows
Forms/ADO.NET code.
Java Comparison:
.NET’s CLR is like Java’s JVM.
BCL is like Java’s standard library (e.g., java.util).
C# syntax is similar to Java, but .NET’s libraries (e.g., Windows Forms)
are Windows-specific.
Difference between struct and enum. Why do we need to handle
the exception? illustrate with example with your own customized
example.
Aspect Struct Enum
A struct (structure) is a value An enum (enumeration) is a
Definition type that groups related data value type that defines a set of
(fields, methods) together. named constants.
Used to create lightweight Used to define a fixed set of
Purpose objects with data and behavior, named values, like days of the
like a small class. week or statuses.
Value type (stored on the stack, Value type (based on an integer,
Type
not heap). e.g., int).
Can have fields, properties, Only contains named constants
Members
methods, constructors. (no methods or complex logic).
Cannot inherit from other
Inheritanc Cannot inherit or be inherited;
structs or classes (but can
e fixed set of values.
implement interfaces).
Usage Representing a Point with x and Defining Days like Monday,
Example y coordinates. Tuesday, etc.
Each instance has its own copy Represents a single constant
Memory
of data (value semantics). value from a predefined set.
No direct equivalent, but Similar to Java’s enum (though
Java
similar to a class with value Java enums can have methods,
Equivalent
semantics. C# enums are simpler).
Why Do We Need to Handle Exceptions?
Exception handling in C# (and .NET) is a way to manage errors that occur
during program execution, like dividing by zero or accessing a file that
doesn’t exist. It uses try, catch, finally, and throw to handle these errors
gracefully.
Why is it Important?
1. Prevents Program Crashes:
o Without exception handling, an error (e.g., invalid user input) can
crash your program. Handling exceptions keeps the program
running by addressing errors.
o Example: If a user enters “abc” instead of a number in a
calculator app, exception handling prevents a crash.
2. Improves User Experience:
o Instead of showing a crash message, you can display a friendly
error message (e.g., “Please enter a valid number”).
o Java Comparison: Java’s try-catch is almost identical to C#’s,
so you’re familiar with this concept.
3. Ensures Resource Cleanup:
o The finally block ensures resources (e.g., files, database
connections) are closed properly, even if an error occurs.
o Example: Closing a file after reading, even if an error happens.
4. Debugging and Reliability:
o Exceptions help identify what went wrong (e.g.,
DivideByZeroException). You can log errors or take alternative
actions, making your app more reliable.
o For Exams: TU Nepal often asks why exception handling is
needed in .NET or to write a try-catch block.
5. Part of .NET’s Managed Environment:
o The Common Language Runtime (CLR) uses exceptions to
manage errors in a structured way, ensuring .NET apps are
robust.
Exception handling code example:
using System;
namespace exception_handling_example
{
internal class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter student name:");
string name = Console.ReadLine();
Console.WriteLine("Enter marks (0-100):");
string input = Console.ReadLine();
// Try to convert input to a number
int marks = Convert.ToInt32(input);
// Check if marks are valid
if (marks < 0 || marks > 100)
{
throw new ArgumentException("Marks must be between 0 and 100.");
}
// Calculate grade
string grade = marks >= 60 ? "Pass" : "Fail";
Console.WriteLine($"{name}'s Grade: {grade}");
}
catch (FormatException)
{
// Handles non-numeric input
Console.WriteLine("Error: Please enter a valid number for marks.");
}
catch (ArgumentException ex)
{
// Handles invalid range
Console.WriteLine($"Error: {ex.Message}");
}
catch (Exception ex)
{
// Catches any other unexpected errors
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
// Always runs, e.g., to clean up resources
Console.WriteLine("Calculation completed.");
}
}
}
}
What is managed code? Give reason to justify the
statement “.NET framework is platform independent and
language interoperability”?
Managed code is code written in a .NET language (like C#) that runs under
the supervision of the Common Language Runtime (CLR) in the .NET
Framework. The CLR manages memory, security, and execution, making
development easier and safer.
Key Features of Managed Code:
1. Garbage Collection: CLR automatically frees memory for unused
objects (like we discussed earlier).
2. Type Safety: Ensures variables are used correctly (e.g., can’t assign a
string to an int).
3. Exception Handling: Uses try-catch to manage errors (as in your
previous question).
4. Security: CLR checks code for permissions, preventing unauthorized
actions (e.g., accessing restricted files).
5. Just-In-Time Compilation (JIT): Converts code to machine
instructions at runtime.
1. Platform Independence
Platform independence means .NET apps can run on different operating
systems (e.g., Windows, Linux, macOS) without major code changes.
Reasons to Justify:
Common Language Runtime (CLR):
o The CLR converts C# code (or other .NET languages) into
Intermediate Language (IL). At runtime, the JIT compiler turns IL
into machine code specific to the OS and hardware.
o Analogy: Think of IL as a universal translator. You write a story
(code) in one language (C#), and the CLR translates it to any
device’s native language (machine code).
.NET Core and .NET 5/6+:
o While the traditional .NET Framework was Windows-specific, .NET
Core (and later .NET 5/6) was designed to run on Windows, Linux,
and macOS.
o For your exam, TU Nepal’s syllabus likely focuses on the .NET
Framework, but mentioning .NET Core’s cross-platform capability
strengthens your answer.
o Example: A C# console app written on Windows can run on
Linux with .NET Core, needing minimal changes.
Java Comparison: Like Java’s “write once, run anywhere” via the
JVM, .NET Core achieves similar portability with the CLR.
Limitation: The traditional .NET Framework (pre-.NET Core) was
mostly Windows-only, so for exam accuracy, clarify that platform
independence improved with .NET Core.
“.NET Framework achieves partial platform independence through the CLR,
which compiles IL to machine code for different systems. .NET Core enhances
this by supporting Windows, Linux, and macOS, similar to Java’s JVM.”
2. Language Interoperability
Language interoperability means multiple programming languages (e.g., C#,
VB.NET, F#) can work together in a .NET app, sharing code and components
seamlessly.
Reasons to Justify:
Common Language Specification (CLS):
o .NET defines CLS, a set of rules that languages must follow to
ensure compatibility. This lets C# code call VB.NET code or vice
versa.
o Example: A C# class can use a library written in VB.NET without
issues.
o Analogy: Think of CLS as a common language (like English) in a
school where students (languages) speak different tongues but
can collaborate using shared rules.
Intermediate Language (IL):
o All .NET languages compile to IL, a common format. The CLR runs
this IL, so it doesn’t care which language was used.
o Example: You can write a library in C#, compile it to IL, and use
it in an F# project.
Base Class Library (BCL):
o All .NET languages share the same BCL (e.g., System.Console),
ensuring consistent functionality across languages.
o Example: Both C# and VB.NET use Console.WriteLine from the
BCL.
Java Comparison: Java doesn’t support multiple languages on the JVM
as seamlessly as .NET does with C#, VB.NET, etc.
“.NET supports language interoperability because all languages compile to IL,
follow CLS rules, and share the BCL. This allows C#, VB.NET, and other .NET
languages to work together in the same app.”
“The .NET Framework is partially platform-independent because the CLR
compiles IL to machine code for different systems, with .NET Core enabling
full cross-platform support (Windows, Linux, macOS). It is language
interoperable because all .NET languages compile to IL, adhere to CLS, and
share the BCL, allowing seamless collaboration between languages like C#
and VB.NET.”
What is the difference between value type and reference
type in C#. Explain the concept of boxing and unboxing
with suitable program.
Aspect Value Type Reference Type
Stores the actual data Stores a reference (address) to
Definition directly in memory (on the the data, which is stored on the
stack). heap.
Allocated on the stack
Memory Allocated on the heap (managed
(faster, smaller memory
Allocation by Garbage Collection).
footprint).
int, float, double, char, bool, class, string, array, interface,
Examples
struct, enum. delegate, object.
Copying creates an Copying copies the reference, not
Assignment
independent copy of the the data (both variables point to
Behavior
data. same object).
Default Has a default (e.g., int = 0,
Default is null.
Value bool = false).
Modification Changes to a copy don’t Changes to the object affect all
Aspect Value Type Reference Type
affect the original. references to it.
Not managed by GC (stack Managed by GC (heap memory is
Garbage
memory is freed cleaned up when no references
Collection
automatically). remain).
Java Similar to Java primitives Similar to Java objects (String,
Comparison (int, double). ArrayList).
Boxing is the process of converting a value type (e.g., int) to a reference type
(e.g., object). This wraps the value type in an object on the heap, allowing it
to be treated as a reference type.
Unboxing is the reverse: extracting the value type from a reference type
(e.g., converting an object back to an int). It requires explicit casting and
must match the original value type.
Code Example:
using System;
using System.Collections;
namespace boxing_vs_unboxing
{
internal class Program
{
static void Main(string[] args)
{
// Boxing: Converting value type (int) to reference type (object)
int marks = 85; // Value type (stack)
object boxedMarks = marks; // Boxing: wraps int into object (heap)
Console.WriteLine($"Boxed: marks = {marks}, boxedMarks = {boxedMarks}");
// Using ArrayList (requires boxing for value types)
ArrayList studentMarks = new ArrayList();
studentMarks.Add(marks); // Boxing: int to object
studentMarks.Add(90); // Boxing: int to object
Console.WriteLine($"ArrayList: {studentMarks[0]}, {studentMarks[1]}");
// Unboxing: Converting object back to int
try
{
int unboxedMarks = (int)boxedMarks; // Unboxing: object to int
Console.WriteLine($"Unboxed: unboxedMarks = {unboxedMarks}");
// Unboxing from ArrayList
int firstMark = (int)studentMarks[0]; // Unboxing
Console.WriteLine($"Unboxed from ArrayList: firstMark = {firstMark}");
// Incorrect unboxing (will throw exception)
string wrongUnbox = (string)boxedMarks; // Causes InvalidCastException
}
catch (InvalidCastException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}
Difference between: passing value by arguments vs
passing value by reference
Pass by Reference
Aspect Pass by Value
(ref/out)
Passes a copy of the data or Passes the memory address
Definition
reference. of the variable.
Changes in method don’t affect the
Effect on Changes in method directly
original (except object contents for
Original affect the original variable.
reference types).
Uses ref (initialized) or out
Syntax No keyword needed (default).
(uninitialized).
When you want the method
When you want to protect the
Use Case to modify the original
original data.
variable.
Passing an int or a string without Passing an int with ref to
Example
ref. update its value.
Direct access to original
Value types: copy on stack.
Memory variable’s memory (stack or
Reference types: copy of reference.
heap).
using System;
namespace pass_by_value_vs_pass_by_reference
{
internal class Program
{
// Pass by Value (for value type)
static void UpdateMarks(int marks)
{
marks += 10; // Changes copy, not original
Console.WriteLine($"Inside UpdateMarks: marks = {marks}");
}
// Pass by Reference (ref)
static void UpdateMarksRef(ref int marks)
{
marks += 10; // Changes original variable
Console.WriteLine($"Inside UpdateMarksRef: marks = {marks}");
}
// Pass by Reference (out)
static void CalculateGrade(int marks, out string grade)
{
grade = marks >= 60 ? "Pass" : "Fail"; // Must assign grade
Console.WriteLine($"Inside CalculateGrade: grade = {grade}");
}
static void Main(string[] args)
{
// Pass by Value
int studentMarks = 75;
Console.WriteLine($"Before UpdateMarks: studentMarks = {studentMarks}");
UpdateMarks(studentMarks);
Console.WriteLine($"After UpdateMarks: studentMarks = {studentMarks}"); // Unchanged
// Pass by Reference (ref)
Console.WriteLine($"\nBefore UpdateMarksRef: studentMarks = {studentMarks}");
UpdateMarksRef(ref studentMarks);
Console.WriteLine($"After UpdateMarksRef: studentMarks = {studentMarks}"); // Changed
// Pass by Reference (out)
string studentGrade;
CalculateGrade(studentMarks, out studentGrade);
Console.WriteLine($"Final Grade: {studentGrade}");
}
}
}
Explain the components of .NET
The .NET Framework is a Microsoft platform for building and running
applications (desktop, web, etc.) using languages like C#. It provides a
structured environment with tools and services to simplify development.
Think of it as a toolbox with various tools working together to build a house
(your application). Below are the key components, explained simply for your
exam.
1. Common Language Runtime (CLR)
The CLR is the core engine of .NET that runs and manages your code.
It’s like the conductor of an orchestra, ensuring everything (memory,
execution, security) works smoothly.
Key Functions:
o Garbage Collection: Automatically frees memory used by
objects no longer needed (e.g., cleaning up unused variables).
o Just-In-Time Compilation (JIT): Converts Intermediate
Language (IL) code to machine code at runtime for the specific
hardware/OS.
o Exception Handling: Manages errors using try-catch blocks to
prevent crashes.
o Type Safety: Ensures variables are used correctly (e.g., no
assigning a string to an int).
o Security: Enforces permissions to prevent unauthorized actions
(e.g., accessing restricted files).
Java Comparison: CLR is similar to Java’s JVM (Java Virtual Machine),
managing code execution and memory.
Exam Note: TU Nepal often asks about CLR’s role. Mention it’s the
runtime environment for managed code.
2. Base Class Library (BCL)
A collection of pre-built classes and methods you can use in your C#
programs, like a library of ready-made tools.
Examples:
o System: Basic functions like Console.WriteLine.
o System.IO: File operations (e.g., reading/writing files).
o System.Data: Database access (e.g., ADO.NET for SQL Server).
o System.Collections: Data structures like lists, arrays.
Purpose: Saves time by providing reusable code for common tasks
(e.g., file handling, networking).
Java Comparison: Like Java’s standard library (e.g., java.util, java.io).
Exam Note: Highlight that BCL is shared across all .NET languages
(C#, VB.NET) for consistency.
3. Common Language Specification (CLS)
A set of rules that .NET languages (C#, VB.NET, etc.) must follow to
ensure they work together seamlessly.
Purpose: Enables language interoperability, meaning code written
in C# can use a VB.NET library, as all compile to the same
Intermediate Language (IL).
Analogy: CLS is like a common language (English) in a school where
students (languages) speak different tongues but can collaborate.
Exam Note: Mention CLS ensures language interoperability, a
key .NET feature.
4. Common Type System (CTS)
Defines how data types (e.g., int, string, classes) are declared, used,
and managed in .NET.
Types:
o Value Types: Store data directly (e.g., int, struct).
o Reference Types: Store references to data (e.g., class, string).
Purpose: Ensures all .NET languages use consistent data types,
enabling interoperability.
Example: An int in C# is the same as an Integer in VB.NET, thanks to
CTS.
Java Comparison: Similar to Java’s type system, but CTS supports
multiple languages.
Exam Note: CTS is often paired with CLS in questions about
interoperability.
5. .NET Framework Class Library (FCL)
A broader set of libraries built on top of BCL, providing specialized tools
for specific applications.
Key Libraries:
o Windows Forms: For building desktop GUIs (e.g., forms with
buttons, textboxes).
o ASP.NET: For web applications.
o ADO.NET: For database connectivity (e.g., SQL Server).
o WPF: For advanced desktop UIs.
Purpose: Extends BCL with tools for specific tasks, like creating a login
form or connecting to a database.
Exam Note: TU Nepal syllabus often emphasizes Windows Forms and
ADO.NET for BCA.
6. Intermediate Language (IL) and Metadata
What It Is:
o IL: A platform-independent code that C# (or other .NET
languages) compiles into. The CLR converts IL to machine code
via JIT.
o Metadata: Information about the code (e.g., types, methods),
stored with IL, used by the CLR for execution and type safety.
Purpose: IL enables platform independence (run on different
OS/hardware with .NET Core), and metadata supports reflection and
debugging.
Analogy: IL is like a recipe written in a universal language; the CLR
(chef) turns it into a dish (machine code) for your device.
Java Comparison: IL is like Java’s bytecode.
7. Assemblies
What It Is: The compiled output of .NET code, stored as .dll (libraries)
or .exe (executables), containing IL and metadata.
Types:
o Private Assemblies: Used by a single application.
o Shared Assemblies: Stored in the Global Assembly Cache
(GAC) for multiple apps.
Purpose: Packages code for deployment and reuse.
Exam Note: Mention assemblies are the building blocks of .NET apps.
How virtual method is used to achieve dynamic binding in
C#? Explain with the help of suitable program.
In C#, virtual methods are used to achieve dynamic binding through
polymorphism. When a method is declared as virtual in a base class, it can
be overridden in a derived class. This allows the program to determine at
runtime which method to call based on the actual object type, rather than
the reference type.
Virtual Method: A method marked with the keyword virtual in the base
class. It means: "This method can be overridden in a derived class."
Dynamic Binding means deciding at runtime which method to call.
using System;
namespace Dynamic_binding_using_virtual_method
{
internal class Program
{
public class Animal
{
public virtual void Speak()
{ Console.WriteLine("Animal speaks"); }
}
public class Dog : Animal
{
public override void Speak()
{ Console.WriteLine("Dog barks"); }
}
public class Cat : Animal
{
public override void Speak()
{ Console.WriteLine("Cat meows"); }
}
static void Main(string[] args)
{
Animal myAnimal;
myAnimal = new Dog();
myAnimal.Speak();
myAnimal = new Cat();
myAnimal.Speak();
}
}
}
What is string interpolation?
String Interpolation means inserting values directly into a string in a clean
and readable way. String interpolation is a feature in C# that allows you to
create formatted strings in a more readable and concise way. It uses the `$`
symbol before the string literal, allowing you to embed expressions directly
within the string.
static void Main(string[] args)
{
string name = "Anjan";
int age = 21;
string message = $"My name is {name} and I am {age} years old.";
Console.WriteLine(message);
}
Write a C# program to illustrate multi-level inheritance
with virtual method.
using System;
namespace multi_level_inheritance_with_virtual_method
{
internal class Program
{
class Animal
{
public virtual void Speak()
{ Console.WriteLine("Animal speaks"); }
}
class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}
class Puppy : Dog // Further derived class
{
public override void Speak()
{
Console.WriteLine("Puppy yaps");
}
}
static void Main(string[] args)
{
Animal myAnimal = new Animal();
myAnimal.Speak();
Dog myDog = new Dog();
myDog.Speak();
Puppy myPuppy = new Puppy();
myPuppy.Speak();
}
}
}
What is an event? Explain with suitable program, how
event is handled in C#.
An event is a way for a class to notify other classes or parts of the program
when something happens. It's based on the publisher-subscriber model,
where the publisher raises the event, and subscribers handle it.
An event in C# is a mechanism that allows an object to notify other objects
when something happens (e.g., a button is clicked, a key is pressed). It’s part
of the .NET Framework’s event-driven programming model, commonly used
in GUI applications like Windows Forms.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Event_handling
{
internal class Program
{
public delegate void Notify();
public class Process
{
public event Notify ProcessCompleted;
public void StartProcess()
{
Console.WriteLine("Process Started!");
System.Threading.Thread.Sleep(2000);
OnProcessCompleted();
}
protected virtual void OnProcessCompleted()
{ ProcessCompleted?.Invoke(); }
}
public class Subscriber
{
public void OnProcessCompleted()
{ Console.WriteLine("Process Completed!"); }
}
static void Main(string[] args)
{
Process process = new Process();
Subscriber subscriber = new Subscriber();
process.ProcessCompleted += subscriber.OnProcessCompleted;
process.StartProcess();
}
}
}
What is Lambda expression?
A Lambda Expression is a shorter way to write anonymous methods
(methods without a name). It’s used mostly when you want to pass behavior
(a function) as data.
Types of lamda expression:
1. Expression Lambdas:
These are used to create simple functions that consist of a single
expression. Returns a value. Used when the body contains a single
expression.
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // Output: 8
2. Statement Lambdas:
These allow you to write more complex functions that contain multiple
statements. Used when the logic requires multiple statements. Must use
curly braces {} and an explicit return if it returns a value.
Func<int, int, int> multiply = (x, y) =>
{
int result = x * y;
return result;
};
Console.WriteLine(multiply(4, 6)); // Output: 24
Lamda expression example code:
using System;
namespace lamda_expression
{
internal class Program
{
static void Main(string[] args)
{
// Lambda expression: A Lambda Expression is a shorter way to write anonymous methods (methods without
a name). It’s used mostly when you want to pass behavior (a function) as data.
// Func<int, int>: This means a function that takes int input and returns int.
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
//with list and filtering
List<int> numbers = new List<int> { 1, 5, 8, 2, 10, 3 };
// Find even numbers using lambda
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var n in evenNumbers)
{
Console.WriteLine(n);
}
}
}
}
What do you mean by static class and constructor? Explain
with suitable example
A static class is a class that: Cannot be instantiated (you can’t create
objects from it). Can only contain static members (static methods, variables,
properties, etc.).it is used when you want to group utility or helper methods.
Static class example:
static class MyClass
{
public static void MyMethod()
{
Console.WriteLine("This is a static method");
}
}
A constructor is a special method that is called when an instance of a class
is created. It is used to initialize the object's properties or perform any setup
needed when the object is created.
Constructer Example:
using System;
namespace Constructer
{
internal class Program
{
class Car
{
public string model;
public Car()
{
this.model = "MUSTANG";
}
}
static void Main(string[] args)
{
Car car = new Car();
Console.WriteLine(car.model);
Console.ReadKey();
}
}
}
Define constructor. Explain different types of constructors
used in C# with example.
A constructor in C# is a special method that is called when an instance of a
class is created. It has the same name as the class and does not have a
return type. Constructors are used to initialize the object's state and can set
default values for fields or perform any setup required.
There are several types of constructors in C#:
1. Default Constructor:
This constructor does not take any parameters. If you do not define any
constructor, C# provides a default constructor automatically.
public class Car
{
public string Model { get; set; }
public Car()
{
Model = "Unknown";
}
}
2. Parameterized Constructor:
This constructor takes parameters to allow the initialization of an object with
specific values. Example:
class Car
{
public string Model;
public Car(string model)
{
Model = model;
}
}
3. Static Constructor:
This constructor is used to initialize static members of the class. It cannot
take parameters and is called automatically before any static members are
accessed or any instances of the class are created.
public class Car
{
public static int NumberOfWheels;
static Car()
{ NumberOfWheels = 4; }
}
4. Copy Constructor:
This constructor creates a new object as a copy of an existing object. It takes
an instance of the same class as a parameter.
using System;
class Person
{
public string name;
// Parameterized constructor
public Person(string n)
{
name = n;
}
// Copy constructor
public Person(Person obj)
{
name = obj.name;
}
public void Show()
{
Console.WriteLine("Name: " + name);
}
}
class Program
{
static void Main()
{
Person p1 = new Person("Anjan");
Person p2 = new Person(p1); // Copy constructor
p2.Show(); // Output: Name: Anjan
}
}
Define operator overloading. Write a C# program to
overload binary operator.
Operator overloading in C# allows you to define how operators behave for
user-defined types. This means you can specify what happens when we use
an operator with instances of your custom types, making your code more
intuitive and easier to read.
Here's a simple example of overloading the binary `+` operator for a custom
class called `Point. The rules is Use the operator keyword. Overloading must
be done inside the class. Not all operators can be overloaded (e.g., =, &&, ||
can’t be directly overloaded).
Operator overloading allows you to redefine the meaning of an operator (like
+, -, *, etc.) for your custom class.
using System;
class Point
{
public int x, y;
// Constructor
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
// Overloading the + operator
public static Point operator +(Point p1, Point p2)
{
return new Point(p1.x + p2.x, p1.y + p2.y);
}
// Display method
public void Show()
{
Console.WriteLine($"x = {x}, y = {y}");
}
}
class Program
{
static void Main()
{
Point point1 = new Point(3, 4);
Point point2 = new Point(5, 7);
Point result = point1 + point2; // Using overloaded +
Console.WriteLine("Result of adding two points:");
result.Show(); // Output: x = 8, y = 11
}
}
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.
In C#, optional parameters allow you to call a method without explicitly
passing all arguments. If you don’t provide a value for an optional parameter,
the compiler uses a default value that is defined in the method declaration.
Example:
using System;
class Program
{
// Method with an optional parameter
static void Greet(string name = "Guest")
{
Console.WriteLine("Hello, " + name);
}
static void Main()
{
Greet(); // Output: Hello, Guest
Greet("Anjan"); // Output: Hello, Anjan
}
}
Enumerations:
using System;
namespace EnumExample
{
enum Department
{
ComputerScience,
Mathematics,
Physics,
Chemistry
}
enum College
{
Engineering,
Arts,
Science,
Business
}
class Program
{
static void DisplayDepartments()
{
Console.WriteLine("Departments:");
foreach (var dept in Enum.GetValues(typeof(Department)))
{ Console.WriteLine(dept); }
}
static void DisplayColleges()
{
Console.WriteLine("Colleges:");
foreach (var college in Enum.GetValues(typeof(College)))
{ Console.WriteLine(college); }
}
static void Main(string[] args)
{
DisplayDepartments();
DisplayColleges();
}
}
}
List any five contextual keywords in C#? Write a C#
program to initialize and display jagged array elements
with sum of each row.
A contextual keyword in C# is a word that acts like a keyword (i.e., has
special meaning) only in certain contexts, but can also be used as an
identifier (variable/class/method name) in other contexts. It is not reserved
like a regular keyword (int, class, if, etc.), so it can be used as a name when
not being used in its special context.
Contextual keywords were introduced in C# to enable new features without
breaking existing code.
If a feature (like LINQ or async/await) requires a keyword like from,
select, or await, making them reserved would cause problems in older
codebases that already used those names for variables or methods.
So, Microsoft chose to make them contextual, so they act like keywords
only when the compiler expects them to be used as such.
Keyword Context Used
In type inference (e.g., var
Var
x = 10)
from, select,
In LINQ expressions
where
In asynchronous
async, await
programming
Partial In partial classes/methods
Record In record declarations
Yield In iterator methods
add, remove In event accessors
When In switch pattern matching
In set accessors of
Value
properties
Sum of each row using jagged array:
int[][] studentMarks = new int[3][]; // Declare a jagged array with 3 rows
studentMarks[0] = new int[] { 80, 90 }; // Student 1: 2 test scores
studentMarks[1] = new int[] { 70, 85, 60, 95 }; // Student 2: 4 test scores
studentMarks[2] = new int[] { 75 }; // Student 3: 1 test score
// Display the jagged array and calculate row sums
Console.WriteLine("Student Marks and Row Sums:"); // Print header
for (int i = 0; i < studentMarks.Length; i++) // Loop through main array
{
int rowSum = 0; // Initialize sum for current row
Console.Write($"Student {i + 1}: "); // Print student number
for (int j = 0; j < studentMarks[i].Length; j++) // Loop through sub-array
{
Console.Write($"{studentMarks[i][j]} "); // Print each mark
rowSum += studentMarks[i][j]; // Add mark to row sum
}
Console.WriteLine($"| Sum: {rowSum}"); // Print sum for the row
}
What is a Finalizer in C#?
A finalizer (also known as a destructor) is a special method in C# that is
automatically invoked when an object is garbage collected, i.e., just before
the object is removed from memory.
In C#, finalizers are mainly used to release unmanaged resources (like file
handles, database connections, or memory allocated via unmanaged code)
that the .NET garbage collector (GC) does not know how to handle.
a finalizer is declared using a tilde ~
Releasing unmanaged resources: GC manages managed memory,
but not unmanaged resources. Finalizers help bridge that gap.
Logging or tracking object destruction : Developers sometimes
use finalizers for debugging purposes to check when an object is
destroyed.
Fallback cleanup
Example:
using System;
class FileHandler
{
private string fileName;
public FileHandler(string name)
{
fileName = name;
Console.WriteLine("Opening file: " + fileName);
// Simulate opening a file
}
~FileHandler()
{
Console.WriteLine("Finalizer: Closing file " + fileName);
// Simulate closing a file or releasing resources
}
}
class Program
{
static void Main()
{
FileHandler f = new FileHandler("data.txt");
// f goes out of scope here
}
}
What is LINQ (Language Integrated Query)?
LINQ stands for Language Integrated Query. It is a powerful feature in C# and
other .NET languages that allows you to write queries (like SQL) directly
within your code to access data from different sources like:
Arrays
Lists
XML
Databases
Collections
LINQ brings query capabilities directly into C#, making it easier and more
readable to work with data.
Before LINQ, querying different types of data required different approaches:
For databases, you used SQL queries.
For XML, you used XPath or XQuery.
For objects, you had to use loops and conditions.
This inconsistency made code harder to read and maintain.
LINQ solves this by offering a unified syntax to query all these data sources.
Key Features of LINQ:
1. Readability – Makes code cleaner and more understandable.
2. Strongly typed – Errors are caught at compile time, not runtime.
3. Intellisense support – Helps while writing code in Visual Studio.
4. Integration with .NET – You can use it on any data collection in .NET.
5. Reduced code – No need for boilerplate code to loop or filter data.
LINQ operators
LINQ Operator Description
Where Filters elements based on a condition.
Projects each element into a new form (used for selecting
Select
specific fields).
OrderBy Sorts elements in ascending order.
OrderByDescendi
Sorts elements in descending order.
ng
GroupBy Groups elements that share a common key.
Join Joins two sequences based on a key.
Distinct Removes duplicate elements.
Returns a specified number of elements from the start of a
Take
sequence.
Example:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>() { 10, 20, 30, 40, 50 };
// LINQ query to get numbers greater than 25
var result = from n in numbers
where n > 25
select n;
foreach (var num in result)
{
Console.WriteLine(num);
}
}
}
What are Generics in C#?
Generics allow you to create classes, methods, interfaces, and delegates
with a placeholder for the data type. This makes your code type-safe,
reusable, and flexible. Generics mean “write once, use for any data type.”
Without generics, you'd have to write multiple versions of the same method
or class for different data types. Generics help you:
Avoid code duplication
Improve performance (no boxing/unboxing)
Catch type errors at compile-time / Compile type safety
Create reusable, type-safe code
using System;
// We use < > to specify Parameter type
public class GFG<T>
{
// private data members
private T data;
// using properties
public T value
{
// using accessors
get
{
return this.data;
}
set
{
this.data = value;
}
}
}
// Driver class
class Test
{
// Main method
static void Main(string[] args)
{
// instance of string type
GFG<string> name = new GFG<string>();
name.value = "GeeksforGeeks";
// instance of float type
GFG<float> version = new GFG<float>();
version.value = 5.0F;
// display GeeksforGeeks
Console.WriteLine(name.value);
// display 5
Console.WriteLine(version.value);
}
}
Differentiate OOP and Object based programming
Object-Oriented Object-Based
Feature
Programming (OOP) Programming
A programming paradigm A programming approach that
Definition based on the concept of uses objects but doesn't
objects and classes. support classes fully.
Supports
✔ Yes ✖ No
Inheritance
Supports
✔ Yes ✖ No or Limited
Polymorphism
Supports
✔ Yes ✔ Yes
Encapsulation
Supports
✔ Yes ✖ No or Limited
Abstraction
Supports
✔ Only Objects (not full class
Classes & ✔ Both
support)
Objects
Example
C++, Java, C#, Python JavaScript (pre-ES6), VBScript
Languages
Object-Oriented Object-Based
Feature
Programming (OOP) Programming
Access ✔ Fully supported (private,
✖ Not fully supported
Modifiers public, protected, etc.)
Example Java using class Car {} JavaScript using let car = {}
What is interface?
An interface is a completely "abstract class", which can only contain abstract
methods and properties (with empty bodies). An interface is like a contract
or a blueprint.
It only contains method signatures (no method body).
A class that implements an interface must provide the body for all
methods.
Interfaces are used to achieve abstraction and multiple inheritance.
It is considered good practice to start with the letter "I" at the beginning of an
interface, as it makes it easier for yourself and others to remember that it is an
interface and not a class.
By default, members of an interface are abstract and public.
Note: Interfaces can contain properties and methods, but not fields.
// Interface
using System;
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
What is Delegate?
A delegate is like a pointer to a function. Store a method as a variable. Call
that method later Allow you to pass methods as parameters. A delegate is an
object which refers to a method or you can say it is a reference type variable
that can hold a reference to the methods. It provides a way which tells which
method is to be called when an event is triggered.
Think of a delegate like a remote control.
The remote doesn’t do anything on its own, but it tells the TV what to do
(turn on, change volume, etc.).
For example, if you click on a Button on a form (Windows Form
application), the program would call a specific method. In simple words, it is
a type that represents references to methods with a particular parameter list
and return type and then calls the method in a program for execution when it
is needed.
Delegate type can be declared using the delegate keyword. Once a
delegate is declared, delegate instance will refer and call those methods
whose return type and parameter-list matches with the delegate declaration.
Types of Delegate:
1. Single Cast Delegate
A single cast delegate can refer to one method at a time.
Example:
using System;
public delegate void MyDelegate(); // Declaring delegate
class Program
{
public static void SayHello()
{
Console.WriteLine("Hello!");
}
static void Main()
{
MyDelegate del = SayHello; // Assigning method
del(); // Invoking
}
}
2. Multicast Delegate
A multicast delegate holds references to multiple methods, and invokes
them in sequence.
Only methods with void return type are safe to use with multicast.
Example:
using System;
public delegate void MyDelegate(); // Declaring delegate
class Program
{
public static void Method1()
{
Console.WriteLine("Method1 called");
}
public static void Method2()
{
Console.WriteLine("Method2 called");
}
static void Main()
{
MyDelegate del = Method1;
del += Method2; // Adding another method
del(); // Calls Method1 then Method2
}
}
3. Generic Delegates
C# provides three built-in generic delegates:
Delegate Syntax
Description
Type Example
Func<int, int,
Func<> Returns a value
int>
Action<> Returns void Action<string>
Returns bool (used for
Predicate<> Predicate<int>
conditions/predicates)
Example:
using System;
class Program
{
static int Add(int a, int b) => a + b;
static void Print(string message) => Console.WriteLine(message);
static bool IsEven(int x) => x % 2 == 0;
static void Main()
{
Func<int, int, int> sum = Add;
Console.WriteLine("Sum: " + sum(3, 4));
Action<string> show = Print;
show("Hello from Action");
Predicate<int> isEven = IsEven;
Console.WriteLine("Is 4 even? " + isEven(4));
}
}
What is meant by system exception
In C#, a System Exception is a type of runtime error that is generated by
the .NET runtime when something goes wrong during the execution of a
program. These exceptions are derived from the base class
System.Exception.
System exceptions are usually caused by:
Invalid operations
Faulty logic
Problems during runtime (e.g., divide by zero, null reference, index out
of bounds)
Exception Type Description
DivideByZeroException Trying to divide by zero
NullReferenceException Using an object that is null
IndexOutOfRangeExcep
Accessing array with invalid index
tion
Trying to cast an object to an
InvalidCastException
incompatible type
Exception Type Description
FileNotFoundException Trying to access a file that doesn’t exist
When a number exceeds the storage
OverflowException
capacity
Code Example:
using System;
class Program
{
static void Main()
{
try
{
int x = 5;
int y = 0;
int result = x / y; // This will throw DivideByZeroException
}
catch (DivideByZeroException e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
What is a variable size array? Write a program to create
multi dimensional array to store the marks of 3 students
on different subjects first student has marks of 3 subject
sencond has marks of 4 and third has marks of 2. Dislay
the subject marks and average marks for each student.
A variable size array (also called a jagged array) is an array where each row
(in a 2D structure) can have a different number of elements. Unlike a
traditional 2D array (which has equal columns in all rows), a jagged array
allows different lengths of sub-arrays.
using System;
class Program
{
static void Main()
{
// Declare a jagged array where each element is an array of marks
int[][] marks = new int[3][];
// Initialize each student's marks with different subject counts
marks[0] = new int[] { 85, 90, 78 }; // Student 1 - 3 subjects
marks[1] = new int[] { 88, 76, 92, 81 }; // Student 2 - 4 subjects
marks[2] = new int[] { 95, 89 }; // Student 3 - 2 subjects
// Display marks and calculate averages
for (int i = 0; i < marks.Length; i++)
{
Console.WriteLine($"Student {i + 1} marks:");
int total = 0;
for (int j = 0; j < marks[i].Length; j++)
{
Console.WriteLine($"Subject {j + 1}: {marks[i][j]}");
total += marks[i][j];
}
double average = (double)total / marks[i].Length;
Console.WriteLine($"Average: {average:F2}\n");
}
}
}
What is Static binding?
Static binding means the method or function call is resolved at compile time.
The compiler knows which method or property to call before the program is
run.
This happens when:
The method is not virtual.
The method is not overridden in a derived class.
Method overloading (same method name, different parameters) is also
resolved using static binding.
It does not support polymorphism.
Feature Static Binding Dynamic Binding
When decided Compile Time Runtime
Keyword used No special keyword virtual and override
Performance Faster Slightly slower
Example use case Method overloading Method overriding
Code Example:
using System;
class Animal
{
public void Speak()
{
Console.WriteLine("The animal speaks.");
}
}
class Dog : Animal
{
// This is not an override. It's a new method.
public void Speak()
{
Console.WriteLine("The dog barks.");
}
}
class Program
{
static void Main()
{
Animal a = new Dog();
a.Speak(); // Output: "The animal speaks." - static binding (compile time decides to use
Animal's Speak)
}
}
Write a C# program to select the odd and divisible by 3
number from list of number (1-30) using LINQ Query.
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a list of numbers from 1 to 30
List<int> numbers = Enumerable.Range(1, 30).ToList();
// Use LINQ query to select numbers that are odd and divisible by 3
var result = from num in numbers
where num % 2 != 0 && num % 3 == 0
select num;
// Display the result
Console.WriteLine("Numbers from 1 to 30 that are odd and divisible by 3:");
foreach (var number in result)
{
Console.Write(number + " ");
}
}
}
Write C# program to overload unary (++) and relational
(==) operator.
using System;
class Counter
{
private int count;
// Constructor to initialize count
public Counter(int value)
{
count = value;
}
// Display method to show current value
public void Display()
{
Console.WriteLine("Count = " + count);
}
// Overload ++ operator (Unary Increment)
public static Counter operator ++(Counter c)
{
// Increment the internal count and return updated object
c.count++;
return c;
}
// Overload == operator (Relational Equality)
public static bool operator ==(Counter c1, Counter c2)
{
// If both null, return true
if (ReferenceEquals(c1, c2))
return true;
// If one is null, return false
if (ReferenceEquals(c1, null) || ReferenceEquals(c2, null))
return false;
// Compare internal count values
return c1.count == c2.count;
}
// Overload != because == must be paired with !=
public static bool operator !=(Counter c1, Counter c2)
{
return !(c1 == c2);
}
// Override Equals and GetHashCode for proper == support
public override bool Equals(object obj)
{
if (obj is Counter)
{
return this == (Counter)obj;
}
return false;
}
public override int GetHashCode()
{
return count.GetHashCode();
}
}
class Program
{
static void Main()
{
// Create two Counter objects
Counter c1 = new Counter(5);
Counter c2 = new Counter(5);
// Display original values
Console.WriteLine("Original Values:");
c1.Display();
c2.Display();
// Test relational (==) operator
Console.WriteLine("\nAre c1 and c2 equal? " + (c1 == c2)); // true
// Use overloaded ++ operator
++c1;
Console.WriteLine("\nAfter incrementing c1:");
c1.Display();
// Test relational (==) operator again
Console.WriteLine("\nAre c1 and c2 equal now? " + (c1 == c2)); // false
}
}
DB connection:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
// Connection string — change this based on your SQL Server setup
string connectionString = "Data Source=localhost;Initial Catalog=YourDatabaseName;Integrated
Security=True";
// SQL insert command
string query = "INSERT INTO Students (Id, Name, Age, Sem) VALUES (@Id, @Name, @Age, @Sem)";
// Values to insert
int id = 101;
string name = "Anjan";
int age = 21;
int sem = 5;
// Establish connection and insert
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(query, conn);
// Add parameters to prevent SQL injection
cmd.Parameters.AddWithValue("@Id", id);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Age", age);
cmd.Parameters.AddWithValue("@Sem", sem);
try
{
conn.Open(); // Open connection
int rows = cmd.ExecuteNonQuery(); // Execute insert
Console.WriteLine($"{rows} row(s) inserted.");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
Differences between indexer and properties
Aspect Indexer Property
Provides access to a single
Allows an object to be indexed
Purpose value or data through
like an array, e.g., obj[0]
obj.PropertyName
Uses this keyword with
Uses a named member:
Syntax parameters: public int this[int
public int Age { get; set; }
index] { get; set; }
Can have one or more
Number of
parameters (supports multi- No parameters allowed
parameters
dimensional indexing)
Accessed like an array element: Accessed like a field:
Access
obj[0] obj.PropertyName
When accessing a single
When an object represents a
Use case piece of data or computed
collection or array-like data
value
Name Has no explicit name; accessed Has an explicit name defined
Aspect Indexer Property
via this keyword and indices by the developer
Example int value = myList[2]; int age = person.Age;
Indexer Example:
using System;
class SampleCollection
{
private int[] arr = new int[5];
public int this[int index]
{
get { return arr[index]; }
set { arr[index] = value; }
}
}
class Program
{
static void Main()
{
var collection = new SampleCollection();
collection[0] = 10; // Using indexer
Console.WriteLine(collection[0]);
}
}
Types of indexer:
Classification Example Syntax Use Case
Array-like
Single-parameter this[int index]
access
2D or matrix-
Multi-parameter this[int x, int y]
like access
Lookup
Read-only get only without
modifying
Setting value,
Write-only set only
no retrieval
Read-write get and set Full access
String-based indexer this[string key] Key-value
Classification Example Syntax Use Case
mapping (e.g.
dictionary)