C# Interview Q&A
Here are the questions from the C# Q&A series:
- Explain the difference between .NET and C#?
- .NET Framework vs .NET Core vs .NET 5.0?
- What is IL (Intermediate Language) Code?
- What is the use of JIT (Just-in-time compiler)?
- Is it possible to view IL code?
- What is the benefit of compiling into IL code?
- Does .NET support multiple programming languages?
- What is CLR (Common Language Runtime)?
- What is managed and unmanaged code?
- Explain the importance of the Garbage Collector?
- Can garbage collector claim unmanaged objects?
- What is the importance of CTS?
- Explain CLS?
- Difference between Stack vs Heap?
- What are Value types & Reference types?
- Explain boxing and unboxing?
- What is the consequence of boxing and unboxing?
- Explain casting, implicit casting, and explicit casting?
- What can happen during explicit casting?
- Differentiate between Array and ArrayList?
- Whose performance is better, Array or ArrayList?
- What are generic collections?
- What are threads (Multithreading)?
- How are threads different from TPL?
- How do we handle exceptions in C# (try/catch)?
- What is the need of finally?
- Why do we need the out keyword?
- What is the need for Delegates?
- What are events?
- What's the difference between Abstract class and Interface?
Part 2: Questions on Delegates, Event & Delegates vs Events
Part 3: Questions on OOP, Abstraction, Encapsulation, Inheritance, Virtual, Overriding, and Overloading
Part 4: Questions on Polymorphism, Static vs Dynamic Polymorphism, and Operator Overloading
Part 5: Tricky Questions around Abstract classes and Interfaces
Part 6: Answering the most asked question "Abstract classes vs Interface"
Part 7: Questions around Constructors & in Parent-Child which constructor fires first
Part 8: Questions around Shadowing, Sealed, Nested classes, and Partial classes
Part 9: Questions around SOLID principles, Dependency Injection (DI), and IoC
Part 10: Explain & Differentiate Composition, Aggregation, and Association in C#
Part 11: Crack questions on Stack, Heap, Boxing, Unboxing, Value & Reference types
Part 12: What is Garbage Collector, Managed vs Unmanaged Code, and Memory Leaks.
1. Explain the difference between .NET and C#?
- .NET is a framework that provides a comprehensive platform for building applications. It includes a runtime (CLR), libraries, and tools for development.
- C# is a programming language used to write applications for the .NET platform. It is object-oriented, type-safe, and is one of the most popular languages used in .NET development.
Example:
- .NET provides a framework to create web applications, APIs, and more.
- C# is used within .NET to write those applications.
2. .NET Framework vs .NET Core vs .NET 5.0?
- .NET Framework: A proprietary framework mainly for Windows-based applications. It is limited to running on Windows.
- .NET Core: A cross-platform, open-source framework that can run on Windows, macOS, and Linux. It is used for creating web applications, microservices, and more.
- .NET 5.0: A unified framework combining .NET Core and .NET Framework. It supports all types of applications and can run on multiple platforms.
3. What is IL (Intermediate Language) Code?
- Intermediate Language (IL) is the low-level code generated by the compiler when C# code is compiled. It is platform-independent and is executed by the CLR (Common Language Runtime) at runtime.
Example: C# code:
This code is compiled into IL code.
4. What is the use of JIT (Just-in-time compiler)?
- JIT compiles the Intermediate Language (IL) code to native machine code at runtime. It helps improve performance by compiling code only when it’s needed, thus optimizing execution.
5. Is it possible to view IL code?
- Yes, you can view IL code using tools like ILSpy or dotPeek. These decompilers can open a compiled assembly (DLL or EXE) and display the IL code inside.
6. What is the benefit of compiling into IL code?
- Platform Independence: IL code can be executed on any platform that has the CLR, making applications highly portable.
- Optimization: The JIT compiler compiles IL code into optimized machine code based on the target environment, improving performance.
7. Does .NET support multiple programming languages?
- Yes, .NET supports multiple languages, including C#, VB.NET, F#, C++/CLI, and others. All of them compile to IL code, which is executed by the CLR.
8. What is CLR (Common Language Runtime)?
- CLR is the runtime environment for executing .NET applications. It provides important services like garbage collection, exception handling, type safety, and JIT compilation.
9. What is managed and unmanaged code?
- Managed Code: Code that runs under the control of the CLR. Example: C# code.
- Unmanaged Code: Code that runs directly on the Windows OS, bypassing the CLR. Example: C++ code.
10. Explain the importance of the Garbage Collector?
- The Garbage Collector (GC) automatically manages memory by reclaiming memory occupied by objects that are no longer in use. It prevents memory leaks and helps in efficient memory management.
11. Can garbage collector claim unmanaged objects?
- No, the garbage collector can only manage managed objects (i.e., those created on the heap). Unmanaged objects (e.g., native pointers) need to be manually freed using the
Dispose
method orFree
function in C++.
12. What is the importance of CTS?
- CTS (Common Type System) defines how types are declared and used in .NET, ensuring type safety and interoperability between different languages.
13. Explain CLS?
- CLS (Common Language Specification) is a subset of the CTS. It defines a set of rules that languages must follow to ensure that code written in different .NET languages can interoperate seamlessly.
14. Difference between Stack vs Heap?
- Stack: Stores value types (like
int
andchar
) and method calls. It is fast and has limited memory. - Heap: Stores reference types (like objects and arrays). It is slower but has a larger memory space, and it is managed by the garbage collector.
15. What are Value types & Reference types?
- Value types: Hold the actual data (e.g.,
int
,char
,struct
). Stored on the stack. - Reference types: Store a reference to the data (e.g.,
class
,array
,string
). Stored on the heap.
16. Explain boxing and unboxing?
- Boxing: Converting a value type (e.g.,
int
) into a reference type (e.g.,object
).
- Unboxing: Converting a reference type back into a value type.
17. What is the consequence of boxing and unboxing?
- Performance Overhead: Boxing involves copying the value type to the heap, which takes time and memory.
- Invalid cast errors: If unboxing is done incorrectly (i.e., mismatched types), it will throw an exception.
18. Explain casting, implicit casting, and explicit casting?
- Casting: Converting one type to another.
- Implicit casting: Done automatically by the compiler when no data loss is involved.
- Explicit casting: Developer-defined conversion, often when data loss might occur.
19. What can happen during explicit casting?
- Data loss: When casting from a larger type to a smaller one, like
double
toint
, the decimal part may be lost. - Exceptions: If the types are incompatible, it may throw a
InvalidCastException
.
20. Differentiate between Array and ArrayList?
- Array: Fixed-size, type-safe collection of elements of the same type.
- ArrayList: Dynamic-size collection that can store elements of different types.
21. Whose performance is better, Array or ArrayList?
- Array generally has better performance than ArrayList because arrays are fixed in size and type-safe, while ArrayList involves type-checking and dynamic resizing.
22. What are generic collections?
- Generic collections are collections that can store any data type without boxing or unboxing. Examples include
List<T>
,Dictionary<TKey, TValue>
, andQueue<T>
.
23. What are threads (Multithreading)?
- Threads allow concurrent execution of code. Multithreading is the process of executing multiple threads in parallel to improve performance, especially for CPU-bound tasks.
24. How are threads different from TPL?
- Threads are lower-level constructs for parallelism and concurrency.
- TPL (Task Parallel Library) is a higher-level abstraction that simplifies thread management and provides easier methods for parallel programming.
25. How do we handle exceptions in C# (try/catch)?
- C# uses the
try
,catch
,finally
blocks to handle exceptions.
26. What is the need of finally?
- The finally block ensures that code inside it is executed regardless of whether an exception was thrown or not, making it ideal for clean-up code (e.g., closing files or releasing resources).
27. Why do we need the out keyword?
- The
out
keyword is used when a method needs to return multiple values. It allows passing parameters by reference, and the parameter must be assigned a value inside the method.
28. What is the need for Delegates?
- Delegates are used to define callback methods or event handlers, allowing methods to be passed as parameters to other methods.
29. What are events?
- Events are a way to provide notifications when something happens. They are typically used with delegates to handle user input or other actions in an application.
30. What's the difference between Abstract class and Interface?
- Abstract class: Can have both methods with implementations and abstract methods. It can provide common functionality.
- Interface: Contains only method signatures (no implementations) and can be implemented by any class.
Part 2: Questions on Delegates, Event & Delegates vs Events
- Delegates are type-safe function pointers used for callback methods.
- Events are used to notify subscribers when something happens.
- Delegates vs Events: Events provide better encapsulation. Delegates can be invoked directly, while events can only be triggered from within the class that declares them.
Part 3: OOP concepts
- Abstraction: Hiding implementation details (e.g., using abstract classes/interfaces).
- Encapsulation: Bundling data and methods that operate on the data (e.g., properties, methods).
- Inheritance: Deriving new classes from existing ones.
- Virtual, Overriding, and Overloading: These are techniques for extending or modifying class behaviors.
Part 4: Polymorphism
- Static Polymorphism: Method overloading.
- Dynamic Polymorphism: Method overriding.
1. Tricky Questions around Abstract classes and Interfaces
Q: Can you instantiate an abstract class?
- Answer: No, you cannot instantiate an abstract class directly. An abstract class is meant to be inherited by other classes. However, you can create an object of a subclass that implements the abstract methods of the abstract class.
Example:
Q: Can an abstract class implement an interface?
- Answer: Yes, an abstract class can implement an interface, and in doing so, it must implement all the methods of the interface or leave them to be implemented by derived classes.
Example:
2. Answering the most asked question "Abstract classes vs Interface"
Abstract Class:
- Can have method implementations (non-abstract methods).
- Can have fields (state).
- Supports constructors.
- A class can inherit only one abstract class due to single inheritance.
Interface:
- Cannot have any method implementations (methods are always abstract, except default methods in C# 8.0 and above).
- Cannot have fields.
- No constructors.
- A class can implement multiple interfaces (supports multiple inheritance).
Example:
3. Questions around Constructors & in Parent-Child which constructor fires first
- Answer: In inheritance, the parent class constructor always fires first, followed by the child class constructor. If the parent class constructor has parameters, they can be called using the
base()
keyword from the child class.
Example:
- Constructor Order: Parent constructor is always called first.
4. Questions around Shadowing, Sealed, Nested classes, and Partial classes
Q: What is shadowing?
- Answer: Shadowing occurs when a member of a derived class has the same name as a member in the base class. You can use the
new
keyword to indicate that a member is intentionally shadowing the base class member.
Example:
Q: What is Sealed?
- Answer: A sealed class cannot be inherited. A sealed method cannot be overridden in derived classes.
Example:
Q: What are Nested Classes?
- Answer: A nested class is a class defined within another class. It can be used for logically grouping classes that are only used in the context of the outer class.
Example:
Q: What are Partial Classes?
- Answer: A partial class allows a class to be split across multiple files. This is useful when working on large projects to organize code better or when auto-generated code needs to be extended.
Example:
5. Questions around SOLID principles, Dependency Injection (DI), and IoC
Q: What are SOLID principles?
- S: Single Responsibility Principle - A class should have only one reason to change.
- O: Open/Closed Principle - A class should be open for extension but closed for modification.
- L: Liskov Substitution Principle - Objects of a superclass should be replaceable with objects of a subclass.
- I: Interface Segregation Principle - No client should be forced to depend on methods it does not use.
- D: Dependency Inversion Principle - High-level modules should not depend on low-level modules. Both should depend on abstractions.
Q: What is Dependency Injection (DI) and Inversion of Control (IoC)?
- DI: A design pattern used to implement IoC. It allows the injection of dependencies into a class, instead of having the class create them internally.
Example (Constructor Injection):
6. Explain & Differentiate Composition, Aggregation, and Association in C#
Composition: A strong "has-a" relationship where the child objects do not exist independently of the parent object. When the parent object is destroyed, the child objects are destroyed too.
Example: A House class that has rooms, and when the house is destroyed, the rooms are destroyed as well.
Aggregation: A weaker form of association where the child objects can exist independently of the parent object.
Example: A Library that contains Books. Books can exist independently of the library.
Association: A relationship where one object uses or interacts with another object, but there is no ownership.
Example: A Person class that has an Address. A person can have multiple addresses, but deleting the person does not delete the address.
7. Crack questions on Stack, Heap, Boxing, Unboxing, Value & Reference types
Q: What is the difference between stack and heap memory?
- Stack: Stores value types (primitive types and local variables), has a LIFO (Last In First Out) structure, and is fast but limited in size.
- Heap: Stores reference types (objects), is dynamic in size, and is slower than stack because of garbage collection.
Q: What is the difference between Value types and Reference types?
- Value types: Directly contain their data. Example:
int
,float
,char
,struct
. - Reference types: Contain a reference (pointer) to the data, stored in the heap. Example:
object
,class
,array
,string
.
Q: What is Boxing and Unboxing?
Boxing: Converting a value type to a reference type.
Example:
Unboxing: Converting a reference type back to a value type.
Example:
8. What is Garbage Collector, Managed vs Unmanaged Code, and Memory Leaks?
Garbage Collector (GC):
- The Garbage Collector (GC) in C# automatically frees up memory by reclaiming unused objects in the heap.
Managed vs Unmanaged Code:
- Managed code: Code that runs under the control of the .NET runtime and is garbage collected.
- Unmanaged code: Code that runs directly on the operating system, like C or C++ code.
Memory Leaks:
- Memory leaks occur when objects are no longer in use but are not properly cleaned up, often due to unintentional references or improper resource management. While the GC handles most cleanup, developers must manage external resources like file handles or database connections.
Comments
Post a Comment