C# Interview Q&A

Here are the questions from the C# Q&A series:

  1. Explain the difference between .NET and C#?
  2. .NET Framework vs .NET Core vs .NET 5.0?
  3. What is IL (Intermediate Language) Code?
  4. What is the use of JIT (Just-in-time compiler)?
  5. Is it possible to view IL code?
  6. What is the benefit of compiling into IL code?
  7. Does .NET support multiple programming languages?
  8. What is CLR (Common Language Runtime)?
  9. What is managed and unmanaged code?
  10. Explain the importance of the Garbage Collector?
  11. Can garbage collector claim unmanaged objects?
  12. What is the importance of CTS?
  13. Explain CLS?
  14. Difference between Stack vs Heap?
  15. What are Value types & Reference types?
  16. Explain boxing and unboxing?
  17. What is the consequence of boxing and unboxing?
  18. Explain casting, implicit casting, and explicit casting?
  19. What can happen during explicit casting?
  20. Differentiate between Array and ArrayList?
  21. Whose performance is better, Array or ArrayList?
  22. What are generic collections?
  23. What are threads (Multithreading)?
  24. How are threads different from TPL?
  25. How do we handle exceptions in C# (try/catch)?
  26. What is the need of finally?
  27. Why do we need the out keyword?
  28. What is the need for Delegates?
  29. What are events?
  30. 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:

csharp
public class Calculator { public int Add(int x, int y) { return x + y; } }

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 or Free 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 and char) 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).
csharp
int num = 5; object obj = num; // Boxing
  • Unboxing: Converting a reference type back into a value type.
csharp
object obj = 5; int num = (int)obj; // Unboxing

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.
csharp
int a = 5; double b = a; // Implicit casting
  • Explicit casting: Developer-defined conversion, often when data loss might occur.
csharp
double a = 5.5; int b = (int)a; // Explicit casting

19. What can happen during explicit casting?

  • Data loss: When casting from a larger type to a smaller one, like double to int, 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.
csharp
int[] numbers = new int[5];
  • ArrayList: Dynamic-size collection that can store elements of different types.
csharp
ArrayList list = new ArrayList(); list.Add(5); list.Add("Hello");

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>, and Queue<T>.
csharp
List<int> numbers = new List<int>(); numbers.Add(5);

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.
csharp
try { int result = 10 / 0; } catch (DivideByZeroException ex) { Console.WriteLine("Error: " + ex.Message); } finally { Console.WriteLine("This will always execute."); }

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.
csharp
public delegate void MyDelegate(string message); public static void PrintMessage(string message) { Console.WriteLine(message); } MyDelegate del = PrintMessage; del("Hello World");

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.
csharp
public abstract class Animal { public abstract void Speak(); } public interface ISwim { void Swim(); }

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:

csharp
public abstract class Animal { public abstract void Speak(); } public class Dog : Animal { public override void Speak() { Console.WriteLine("Woof"); } } // Cannot instantiate Animal directly // Animal animal = new Animal(); // Error Dog dog = new Dog(); // Correct dog.Speak(); // Outputs: Woof

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:

csharp
public interface IAnimal { void Eat(); } public abstract class Animal : IAnimal { public abstract void Eat(); // Must be implemented by a derived class } public class Dog : Animal { public override void Eat() { Console.WriteLine("Dog is eating"); } }

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:

csharp
// Abstract class public abstract class Animal { public abstract void Speak(); public void Breathe() { Console.WriteLine("Breathing..."); } } // Interface public interface ISwimmable { void Swim(); // No implementation } public class Dog : Animal, ISwimmable { public override void Speak() { Console.WriteLine("Woof"); } public void Swim() { Console.WriteLine("Dog is swimming"); } }

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:

csharp
public class Parent { public Parent() { Console.WriteLine("Parent Constructor"); } } public class Child : Parent { public Child() { Console.WriteLine("Child Constructor"); } } Child child = new Child(); // Output: // Parent Constructor // Child Constructor
  • 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:

csharp
public class BaseClass { public void Show() { Console.WriteLine("BaseClass Show"); } } public class DerivedClass : BaseClass { public new void Show() { Console.WriteLine("DerivedClass Show"); } } DerivedClass obj = new DerivedClass(); obj.Show(); // Outputs: DerivedClass Show

Q: What is Sealed?

  • Answer: A sealed class cannot be inherited. A sealed method cannot be overridden in derived classes.

Example:

csharp
public sealed class SealedClass { // Cannot be inherited } public class DerivedClass : SealedClass { } // Error: SealedClass cannot be inherited

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:

csharp
public class OuterClass { public class InnerClass { public void Show() { Console.WriteLine("InnerClass"); } } } OuterClass.InnerClass inner = new OuterClass.InnerClass(); inner.Show(); // Outputs: InnerClass

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:

csharp
// File1.cs public partial class MyClass { public void Method1() { Console.WriteLine("Method1"); } } // File2.cs public partial class MyClass { public void Method2() { Console.WriteLine("Method2"); } }

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):

csharp
public interface IMessageService { void SendMessage(string message); } public class EmailService : IMessageService { public void SendMessage(string message) { Console.WriteLine("Email sent: " + message); } } public class UserController { private readonly IMessageService _messageService; public UserController(IMessageService messageService) { _messageService = messageService; } public void NotifyUser() { _messageService.SendMessage("Hello User"); } } // DI container (e.g., using Microsoft.Extensions.DependencyInjection) IServiceProvider serviceProvider = new ServiceCollection() .AddTransient<IMessageService, EmailService>() .AddTransient<UserController>() .BuildServiceProvider(); var userController = serviceProvider.GetService<UserController>(); userController.NotifyUser(); // Outputs: Email sent: Hello User

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:

    csharp
    int i = 10; object obj = i; // Boxing
  • Unboxing: Converting a reference type back to a value type.

    Example:

    csharp
    object obj = 10; int i = (int)obj; // Unboxing

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

Popular posts from this blog

SQL Query :- Create Tables,Primary key,Foreign key,Merge Statment

AngularJS

GridView Design Using CSS