We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
Ayushi Upadhyay
E2262
C# PRACTICE QUESTIONS
(OOPS Technology in C#
Answer- Object-Oriented Programming (OOP) is a programming
paradigm that revolves around the concept of “objects,” which can
contain data and code to manipulate that data. C# is a versatile language
that fully supports OOP principles.
Collections in e#
Collections in C# are used to store, retrieve, and manipulate groups of
objects. They provide various data structures and algorithms to perform
operations like adding, removing, and searching for elements efficiently
Arrays
List
Dictionary
HashSet
Queue
Stack
Anonymous methods in C#
Anonymous methods in C# allow you to create unnamed methods on the
fly. They're often used for event handling and capturing variables from
their containing scope.
delegate void MyDelegate(int x);
MyDelegate myDelegate = delegate (int x)
{ Console. WriteLine($"Anonymous method: {x}");
iB
myDelegate(10);
Single Multilevel & Multiple Inheritance in
Single Inheritance: A class can inherit from only one base class.‘Multilevel Inheritance: A derived class is created from another derived
class, forming a chain of inheritance.
Multiple Inheritance: C# supports multiple inheritance through
interfaces, where a class can implement multiple interfaces but inherit
from only one class.
Exception Handling
Exception handling in C# is a mechanism that allows you to gracefully
manage and respond to runtime errors or exceptional situations that may
occur during the execution of your program. Here's a quick overview:
Try-Catch Bloc]
. The try block contains the code that might throw an
exception, and the catch block contains the code to handle the
exception.
try
t
// Code that might throw an exception
}
catch (ExceptionType ex)
{
// Code to handle the exception
Purpose: Improve performance by storing frequently accessed
data.
‘Types: In-memory, web, database caching.
Mechanisms: Libraries like MemoryCache, distributed caching.
Benefits: Faster response times, reduced server load.
Profiling:
Purpose: Analyze and optimize program performance.
Tools: Visual Studio Profiler, dotTrace, Performance Monitor.
Types: Performance, memory, concurrency profiling.
Benefits: Identify bottlenecks, memory leaks, and optimize code
ThreadingThreading in C# involves running multiple threads concurrently for
improved performance. Key points:
Thread Basics: Thread class for thread management,
Thread Safety: Ensure data integrity with locks
ThreadPool: Provides a pool of worker threads.
Asyne/Await: Simplifies asynchronous programming,
Background/Foreground Threads: Impact on application exit.
Thread Lifecycle: States and controlling execution.
| explain Method Overloading? |
Method overloading in C# lets you define multiple methods with the same
name but different parameters (types or numbers). It improves code
readability and provides flexibility for handling various scenarios
class Calculator
{
// Method to add two integers
public int Add(int a, int b)
{
return a + b;
)
// Overloaded method to add two doubles
public double Add(double a, double b)
{
return a + b;
}
// Overloaded method to add three integers
public int Add{int a, int b, int ¢)
{
retuma+b+¢
)
}
class Program
{
static void Maing
{
Calculator calculator = new Calculator);int sumint = calculator. Add(S, 10);
Console. WriteLine($"Sum of integers: {sumint)");
double sumDouble = calculator.Add(5.5, 10.5);
Console. WriteLine($"Sum of doubles: sumDouble}");
int sumThreeInts = calculator.Add(5, 10, 15);
Console.WriteLine($"Sum of three integers: (sumThreeints)");
Explain Method Overriding?
Method overriding in C# allows a derived class to provide a specific
implementation for a method that is already defined in its base class.
class Shape
{
public virtual void Draw0)
{
Console.WriteLine("Drawing a shape");
)
)
class Circle : Shape
(
public override void Draw()
(
Console WriteLine("Drawing a circle");
)
)
class Program
{
static void Main()
{
Shape shape = new ShapeQ;
shape.Draw); // Output: Drawing a shape
Circle circle = new CircleQ;
circle.Draw0; // Output: Drawing a circle
// Polymorphism in actionShape anotherShape = new Circle);
anotherShape.DrawQ; // Output: Drawing a circle
)
}
Describe Late binding and Early binding:
Early Binding
- Definition: Resolving the method or function call at compile time.
xample: Method calls are resolved at compile time in languages like
Cc
- Advantage: Better performance as the binding is done at compile time.
Late Binding:
- Definition: Resolving the method or function call at runtime.
- Example: Method calls are resolved at runtime in languages like Python
or when using reflection in C#,
- Advantage: Greater flexibility, dynamic behavior, and adaptability
during runtime.
carly binding is resolved at compile time for better performance, while
late binding is resolved at runtime, offering greater flexibility and
adaptability.
What is Encapsulation?
Encapsulation:
Definition: Bundling data (attributes) and methods (functions) that
operate on the data into a single unit (class).
Purpose: Hides the internal details of an object and restricts direct
access to some of its components, promoting data integrity and modular
design.
Key Concept: Access modifiers like public, private, and
protected control the visibility of members outside the cl
What is Abstraction?
Abstraction:
Definition: Representing the essential features of an object while
hiding the non-essential details.Purpose: Simplifies complex systems by modeling classes based on
their relevant characteristics, emphasizing what an object does rather than
how it does it.
Key Concept: Abstract classes and interfaces in programming provide
a way to define abstract types and enforce a contract for derived classes.
In essence, abstraction involves focusing on the essential aspects of an object
and ignoring unnecessary details, providing a high-level view of the system.
Describe Polymosrphism?
Polymorphism:
Definition: The ability of a class to take on multiple forms.
Typ
. Compile-time Polymorphism (Static Binding): Achieved
through method overloading and early binding,
. Runtime Polymorphism (Dynamic Binding): Achieved through
method overriding and late binding.
// Compile-time polymorphism (method overloading)
class Calculator
{
public int Add(int a, int b) => a+ b;
public double Add(double a, double b)
> a+b;
}
/ Runtime polymorphism (method overriding)
class Shape
t
public virtual void Draw()
onsole. WriteLine("Drawing a shape"
class Circle : Shape
{
public override void Draw()
{
Console. WriteLine("Drawing a circle");
}
}Desribe Inheritance?
Definition: The mechanism by which a class (derived or child class)
inherits properties and behaviors from another class (base or parent class).
+ Key Concepts:
+ Base Class (Parent Class): The class whose members are
inherited.
+ Derived Class (Child Class): The class that inherits from the base
class.
Types:
+ Single Inheritance: A derived class inherits from only one base
class.
+ Multiple Inheritance (via interfaces): A class can implement
multiple interfaces but inherit from only one class.
+ Multilevel Inheritance: A class is derived from another derived
class, forming a chain,
‘What do you undrstand by Interface?
Definition: A contract specifying a set of methods that a class must
implement. It defines a contract for what a class should do but not how it
should do it.
Key Features:
. Methods: Contains method signatures without implementations.
: Abstract: All members are implicitly abstract and public.
. No State: Cannot contain fields or define implementations.
interface [Logger
t
void LogMessage( string message);
}
class ConsoleLogger : Logger
t
public void LogMessage(string message)
t
Console. WriteLine($"Logging to console: {message}");
}
}
Difference between ref and out Keyword?
ref Keyword:Used for passing a parameter by reference.
Variable must be initialized before passing.
Preserves the original value.
out Keyword:
Used for output parameters.
Variable doesn't need to be initialized before passing.
Must be assigned a value within the method,
Difference between const and readonly keywords?
const Keyword:
Compile-time constant.
Must be initialized at the time of declaration.
Value is determined at compile time and cannot change.
readonly Keyword:
Runtime constant.
Can be initialized at the time of declaration or in the constructor.
Value is determined at runtime and can only be changed in the
constructor.
In short, const is a compile-time constant, while readonly is a runtime
constant with a value that can be set in the constructor.
‘What do you understand by single level and Multi-Level inheritance?
Single-Level Inheritance:
One class inherits from only one base class.
Multi-Level Inheritance:
‘A class is derived from another derived class, forming a chain.
‘Why Multiple inheritance isnot possible in CH?
Multiple inheritance is not directly supported in C# to avoid the complications
and ambiguity known as the "diamond problem." The diamond problem‘occurs when a class inherits from two classes that have a common ancestor.
This can lead to confusion about which implementation to choose.
class A { public void Method() { Console.WriteLine(“A"); }}
class B { public void Method) ( Console WriteLine(’B"); }}
dass C:A,B()
7A
Cc=new C0;
Method); // Which Method should be called? A’s or B's?
How we can achieve Multiple Inheritance in GF?
We can achieve Multiple inheritance through interfaces-
interface IA
{
void MethodAQ;
}
interface IB
{
void MethodB();
3
// Implementing multiple interfa
class MyClass : IA, IB
t
public void MethodA()
{
Console. WriteLine("MethodA");
}
public void MethodB()
{
Console. WriteLine("MethodB");
}
}What are the access modifiers in GH?
‘Accessible from any other class or assembly.
private: Accessible only within the same clas
protected: Accessible within the same class or derived classes.
internal: Accessible within the same assembly.
protected internal: Accessible within the same assembly or by
derived classes.
private protected: Accessible within the same assembly and by
derived classes, but only if they are in the same assembly
Access modifiers control the visibility and accessibility of classes,
methods, properties, and other members in C#.
ic and non static class?
Cannot be instantiated.
Contains only static members.
Often used for utility functions.
Non-Static Class:
Can be instantiated
Can contain both static and instance members
Used for creating objects and instances
Generic Collections in C#:
Purpose: Containers that store elements of a specific type, providing type
safety and better performance.
Common Generic Collections:
. ListcT>: Dynamic array that automatically resizes.
. Dictionary=TKey, TValue>: Key-value pair collection.
. Quene: Represents a first-in, first-out (FIFO) collection.
. Stack: Represents a last-in, first-out (LIFO) collection.
. HashSet: Unordered collection with no duplicate elements.
. LinkeaList: Doubly linked list.
Benefits:
. Type safety: Ensures that elements are of the specified type
. Performance: Avoids boxing/unboxing and provides better
performance than non-generic collectionsWhat are the non-Generic collection in CA?
Purpose: Containers that store elements without
enforcing a specific type
Common Non-Generic Collections:
: ArrayList: Resizable array that can store
elements of any type.
: Hashtable: Collection of key-value pairs
without type restrictions.
: Queue: Represents a first-in, first-out (FIFO)
collection,
: Stack: Represents a last-in, first-out (LIFO)
collection.
Drawbacks:
: Lack of type safety: Elements are stored as
object, leading to potential runtime errors,
: Performance: Boxing/unboxing operations
may affect performance.
Explain Constructor ?
‘Why Consturctor is required for a class?
What are the Object of a Class?
What do you mean by Class?
Explain Private Constructor?
Explain Parameterized Constructor?
Explain Copy Constructor?
Explain Default Constructor?
Constructor:
Definition: A special method in a class that is automatically called
when an object of the class is created,
Purpose: Initializes the object, allocates memory, and sets default
values.
Why Constructor is Required:
Initialization: Sets initial values for object properties.
Memory Allocation: Allocates necessary resources.
Default Values: Ensures objects start in a valid state.Object of a Class:
Defini
keyword.
Purpose: Represents a unique occurrence of a class, with its own state
and behavior.
‘A concrete instance of a class created using the new
Class:
Definition: A blueprint or template for creating objects. It defines
properties, methods, and behavior that the objects will have.
Purpose: Encapsulates data and behavior into a single unit.
jate Constructor:
Defini
of the class.
Purpose: Often used in utility classes with only static members,
ensuring no instances are created.
A constructor marked as private to prevent the instantiation
Parameterized Constructor:
Definition: A constructor that takes parameters for initializing object
properties.
Purpose: Allows custom initialization based on provided values.
Copy Constructor:
Defini A constructor that creates a new object by copying values
from an existing object.
Purpose: Enables the creation of a new object with the same state as
an existing one.
Default Constructor:
Definition: A constructor with no parameters.
Purpose: Provides a default way to create objects, especially when no
specific initialization is needed.
‘What do you understand by Destructor
Definition: A special method in a class that is called when an object is
about to be destroyed or deallocated,Purpose: Performs cleanup operations, releases resources, and
performs tasks before an object is removed from memory.
. Called by the garbage collector before object reclamation.
. Used for cleanup and releasing unmanaged resources.
. Implemented in classes using unmanaged resources.
. Allows explicit resource release and controlled cleanup,
. Often implemented through the Disposable interface
. Helps avoid reliance on garbage collector timing for resource
release.
Explain lEnumerable?
‘What is GetEnumerator method?
[Enumerabk
Definition: An interface in C# representing a collection that can be
enumerated (iterated) sequentially.
Namespace: system.Collections
Purpose: Provides a standard mechanism for iterating over elements in
a collection without exposing its underlying structure.
Members:
. GetEnumerator(): Returns an lEnumerator for the collection.
GetEnumerator Method:
Defini
tEnumerator object.
Purpose: Enables the iteration over the collection using foreach or
manually advancing through the elements.
‘A method in the lenumerable interface that returns an
Explain Partial classes in CH?
Definition: A feature that allows a class, struct, or interface to be
defined in multiple files.Purpose: Useful for splitting large classes into smaller, more
manageable parts, especially when generated code is involved
Explain Struct in CH?
Explain Enum in CH?
Struct:
. Value type for lightweight data structures.
. No explicit parameterless constructors.
. Stored directly where declared.
. Suitable for small, simple data,
public struct Point
t
public int X { get;
public int Y { get;
}
et; }
et; }
1/ Usage
Point p = new Point { X= 1, Y =2};
Enum:
. Represents named integer constants.
. Provides symbolic names for related values.
. Enumerated constants are distinct.
. Useful for enhancing code readability.
public enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday1/ Usage
Days today = Days. Wednesday;
‘What is Boxing in C#?
What Is Unboxing in CH?
Boxing:
. Converting a value type to an object.
. Needed when treating a value type as an object.
int num = 4;
‘object boxedNum = num; // Boxing
Unboxing:
. Converting an object back to its original value type.
. Needed when retrieving a value from an object reference.
object boxedNum = 42;
int num = (int)boxedNum; // Unboxing
‘What do you mean by String and String Builder in CA?
String:
. Immutable sequence of characters.
. Concatenation creates new strings.
. Suitable for scenarios where immutability is advantageous.
string name = "John";
string message = greeting + name; // Concatenation creates a new string
StringBuilder:
. Mutable sequence of characters.
. Efficient for concatenation.
. Suitable for scenarios where frequent modifications are needed,
such as building dynamic strings.
StringBuilder sb = new StringBuilder("Hello, ");
sb.Append("John"); // Modifies the existing StringBuilder
string result = sb. ToString(); // Converts StringBuilder to stringWhat is Singleton design pattern in CH?
Definition: A design pattern that ensures a class has only one instance
and provides a global point of access to that instance.
Characteristics:
. Private constructor to prevent instantiation from outside the
class.
. AA private static instance variable to hold the single instance.
. A public static method to provide a global point of access to the
instance.
Can we use multiple catch block in try block in C#?
Yes, in C#, you can use multiple catch blocks in a try block to handle different
types of exceptions. Each catch block is associated with a specific exception
type, and the first catch block that matches the type of the thrown exception
will be executed.
try
{
// Code that may throw exceptions
)
catch (DivideByZeroException ex)
{
// Handle DivideByZeroException
}
catch (Argumentéxception ex)
{
// Handle ArgumentException
}
catch (Exception ex)
{
// Catch-all block for other exceptions
// This should generally be at the end to catch any unhandled exceptions
}