.NET Interview Questions

Total Questions: 39

1. What is C# and .NET

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Basic

A: C# is a modern, object-oriented programming language by Microsoft, ideal for various applications like web e.g. ( Web API, Web), mobile(MAUI), and desktop(MAUI, Blazor, WinUI and WinAppSDK). It is known for its simplicity and strong typing.

.NET is a free, open-source, cross platform, platform by Microsoft for building applications across Windows, macOS, and Linux. It supports languages like C#, F#, and Visual Basic, and offers a unified platform with a rich library for efficient development.

2. What is CLR in and its purpose

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Basic

A: The Common Language Runtime (CLR) is a core component of the .NET framework, serving as the execution engine for .NET applications. It provides a managed execution environment for running .NET programs, offering various services(e.g. memory management, type safety., cross language interoperability and just in time compilation) that enhance application performance and security.

3. Difference b/w .NET Core and .NET Framework

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Basic

A: .NET Core and .NET Framework are both frameworks developed by Microsoft, but they have some key differences, including their versions:

  1. Platform: .NET Framework, with versions ranging from 1.0 to 4.8, primarily runs on Windows. In contrast, .NET Core, starting from version 1.0 and evolving to .NET 5 and beyond (now referred to as .NET 7,8,9), is cross-platform and can run on Windows, macOS, and Linux.

  2. Performance: .NET Framework is traditional and less modular, while .NET Core, especially in its later versions, is more modular and lightweight, potentially offering better performance.

  3. Deployment: .NET Framework has limited flexibility and does not support side-by-side versioning. .NET Core, from its initial versions, offers flexible deployment and supports side-by-side versioning, allowing multiple versions to coexist on the same machine.

  4. Open Source: .NET Framework is primarily developed by Microsoft, whereas .NET Core, from its inception, is open source with significant contributions from the community.

  5. API Surface: .NET Framework includes Windows-specific APIs, while .NET Core, particularly in its earlier versions, excludes certain Windows-specific APIs, such as those for desktop applications. However, with the advent of .NET 5 and later(.NET 6,7,8,9), the platform aims to unify the capabilities of both frameworks.

4. What is garbage collector (GC)

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Basic

A: The Garbage Collector (GC) in .NET is a memory management feature that automatically handles the allocation and release of memory for applications, optimizing performance by reclaiming memory that is no longer in use. This process helps prevent memory leaks and reduces the chances of running out of memory.

The key features of the Garbage Collector include automatic memory management, where the GC automatically frees up memory occupied by objects that are no longer referenced by the application, eliminating the need for manual memory management.

5. Difference between value types and reference types

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Basic

A: In .NET, value types and reference types are two categories of data types that have different characteristics and behaviors:

  • Value Types: Value types store their data directly. They are typically allocated on the stack, and when you assign a value type to a new variable, a copy of the value is made.

Examples of value types include int, float, bool, and struct.

  • Reference Types: Reference types store a reference to their data, which is allocated on the heap. When you assign a reference type to a new variable, you are copying the reference, not the actual data.

Examples of reference types include class, interface, delegate, and string.

6. What is boxing and unboxing?

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Basic

A: In C#, boxing and unboxing let value types act as reference types, and vice versa. They convert between value types and objects.

  • Boxing: Boxing converts a value type to a reference type. A boxed value type is wrapped in an object and stored on the heap, allowing it to act as an object.

  • Unboxing: Unboxing converts a reference type back to a value type. An unboxed object extracts the value and stores it on the stack.

Here’s an example of boxing and unboxing:

int value = 123;

object boxedValue = value;

int unboxedValue = (int)boxedValue;

7. Difference between readonly and const keyword

By : Muhammad Waseem Last edited : 17 Nov 2024 Level: Basic

A: In C#, readonly and const are keywords used to define fields that cannot be modified, but they have different use cases and behaviors.

const: The const keyword is used to declare constant fields or local variables. These fields or variables must be initialized at the time of declaration and cannot be changed thereafter.

const double PI = 3.14;

// Output: 3.14
Console.WriteLine(PI); 

readonly: The readonly keyword is used to declare fields that can only be assigned a value during their declaration or within the constructor of the same class.

public sealed class UsersService
{    
    private readonly IUserRepository _userService;

    public UserService(IUserRepository userService)
    {
        _userService = userService;
    }
}

8. Difference between managed and unmanaged code

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Basic

A: Managed code and unmanaged code are two types of code that can be executed in the .NET environment, each with distinct characteristics and management.

  • Managed Code: Managed code is executed by the Common Language Runtime (CLR). It benefits from services such as garbage collection, exception handling, and type safety provided by the CLR. Managed code is written in languages that are compatible with the .NET framework, such as C# and VB.NET. The CLR manages memory allocation and deallocation, which helps prevent memory leaks and other common programming errors.

  • Unmanaged Code: Unmanaged code is executed directly by the operating system and is not managed by the CLR. It is typically written in languages like C or C++ and requires explicit memory management by the programmer. Unmanaged code can lead to issues such as memory leaks and buffer overflows if not handled carefully. However, it can offer performance benefits and is often used for system-level programming or when interacting with hardware.

9. What are the four pillars of OOP

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Basic

A: The four pillars of Object-Oriented Programming (OOP) are fundamental concepts that define the approach to software design and development. These pillars are:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

10. Difference between out and ref keyword

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Basic

A: In C#, out and ref are keywords that allow you to pass arguments by reference to methods. Here’s a clearer explanation with examples:

out: The method must initialize the out parameter before it returns. The caller does not need to initialize the variable before passing it to the method.

public void GetValues(out int a, out int b)
{
    a = 10;
    b = 20;
}

int x, y;

GetValues(out x, out y);

// Output: x: 10, y: 20
Console.WriteLine($"x: {x}, y: {y}"); 

ref: The caller must initialize the ref parameter before passing it to the method. The method can read and modify the value.

void Increment(ref int number)
{
    number++;
}

int value = 5;
Increment(ref value);
Console.WriteLine($"value: {value}"); // Output: value: 6

11. Difference between var and dynamic keyword

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Basic

A: In C#, both var and dynamic are used for variable declaration, but they serve different purposes and have distinct behaviors.

var: The var keyword is used for implicit type declaration. The type of the variable is determined at compile time based on the assigned value. Once the type is inferred, it cannot be changed. This means that var provides strong typing and the benefits of compile-time type checking. For example:

var number = 10; // number is inferred as int

var text = "Hello"; // text is inferred as string

dynamic: The dynamic keyword allows for dynamic typing, where the type of the variable is resolved at runtime. This provides flexibility but sacrifices compile-time type checking, which can lead to runtime errors if the operations on the variable are not valid. It is useful when interacting with COM objects, dynamic languages, or when the type is not known at compile time. For example:

dynamic obj = 1;

obj = "Now I'm a string"; // obj can change type at runtime

12. Difference between implicit and explicit conversion

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Basic

A: In C#, implicit and explicit conversions are two ways to convert one data type into another, each with its own use cases and requirements.

Implicit Conversion: Implicit conversions are automatically performed by the C# compiler when there is no risk of data loss or overflow. These conversions are safe and do not require any special syntax. For example, converting an int to a long is implicit because a long can hold any value that an int can:

int number = 10;

// Implicit conversion from int to long
long bigNumber = number; 

Explicit Conversion: Explicit conversions, also known as casting, require a cast operator because they may result in data loss or overflow. The programmer must explicitly specify the conversion, indicating that they are aware of the potential risks. For example, converting a double to an int requires explicit conversion:

double decimalNumber = 9.78;

// Explicit conversion from double to int
int wholeNumber = (int)decimalNumber; 

13. How to avoid boxing and unboxing

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Basic

A: In C#, boxing and unboxing can lead to performance overhead due to the additional memory allocation and type conversion processes. To avoid boxing and unboxing, consider the following strategies:

Use Generic Collections: Instead of using non-generic collections like ArrayList, which store elements as objects and require boxing, use generic collections like List<T>. Generic collections store elements in their actual types, eliminating the need for boxing.

List<int> numbers = new List<int> { 1, 2, 3 }; // No boxing occurs

Avoid Using Object Type for Value Types: When you need to store or pass value types, avoid using the object type. Instead, use the specific value type or a generic type parameter.

// Use specific type
void ProcessValue(int value) 
{
    // Process value
}

14. Difference between array and array list

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Basic

A: In C#, both Array and ArrayList are used to store collections of items, but they have some key differences in their behavior and usage:

Array: An Array is a collection of items of a specific type. The size of an array is fixed once it is created, meaning you cannot add or remove elements after its creation. Arrays provide better performance due to their fixed size and type safety, as they store elements of a single data type.

int[] numbers = new int[3] { 1, 2, 3 };

ArrayList: An ArrayList is a collection that can store items of any type, as it stores elements as objects. Unlike arrays, the size of an ArrayList is dynamic, allowing you to add or remove elements at runtime. However, this flexibility comes at the cost of performance and type safety, as boxing and unboxing are required for value types.

ArrayList list = new ArrayList();

list.Add(1);

list.Add("two");

list.Add(3.0);

15. Difference between for and foreach loop

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Basic

A: In C#, both for and foreach loops are used to iterate over collections, but they have some key differences in their behavior and usage:

  • for Loop: The for loop is a control flow statement that allows code to be executed repeatedly based on a condition.It is suitable for scenarios where you need to deal with indexes

    int[] numbers = { 1, 2, 3 };
    
    for (int i = 0; i < numbers.Length; i++)
    {
        Console.WriteLine(numbers[i]);
    }
    
  • foreach Loop: The foreach loop is a simpler and more readable way to iterate over elements in a collection(e.g. list). It is specifically designed for iterating through collections and does not require an index.

    List<int> numbers = new List<int>{ 1, 2, 3 };
    foreach (int number in numbers)
    {
        Console.WriteLine(number);
    }
    

16. Difference between overloading and overriding

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Basic

A: In C#, overloading and overriding are two distinct concepts used to achieve polymorphism, but they serve different purposes and are used in different contexts.

  • Overloading: Method overloading occurs when multiple methods have the same name but differ in the type or number of their parameters. It allows a class to have more than one method with the same name, as long as their parameter lists are different. Overloading is resolved at compile time.

    public class MathOperations
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    
        public double Add(double a, double b)
        {
            return a + b;
        }
    
        public int Add(int a, int b, int c)
        {
            return a + b + c;
        }
    }
    
  • Overriding: Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. To override a method, the method in the base class must be marked with the virtual keyword, and the method in the derived class must use the override keyword. Overriding is resolved at runtime.

    public class Animal
    {
        public virtual void MakeSound()
        {
            Console.WriteLine("Some generic animal sound");
        }
    }
    
    public class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Bark");
        }
    }
    

17. Difference between virtual and override keyword

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Basic

A: In C#, the virtual and override keywords are used in the context of method overriding, which is a key aspect of achieving polymorphism in object-oriented programming.

virtual: The virtual keyword is used in a base class to indicate that a method can be overridden in any derived class. It allows the derived class to provide a specific implementation of the method. A method marked as virtual provides a default implementation, but it can be replaced by an overriding method in a subclass.

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Some generic animal sound");
    }
}

override: The override keyword is used in a derived class to provide a new implementation of a method that is declared as virtual in the base class. This allows the derived class to modify or extend the behavior of the base class method.

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

18. When to choose dictionary over list

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Basic

A: Choose a dictionary over a list when you need:

  • Key-Value Storage: For fast lookups and modifications based on unique keys.

  • Unique Keys: To prevent duplicates in your data.

  • Fast Access: O(1) average time complexity for lookups.

  • Dynamic Data: More efficient for frequently changing datasets.

  • Performance Trade-off: Higher memory usage is often justified by faster key-based access.

19. When to use while loop and for

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Basic

A: In C#, both while and for loops are used to execute a block of code repeatedly, but they are suited for different scenarios based on the nature of the iteration.

  • while Loop: The while loop is ideal when the number of iterations is not known beforehand and depends on a condition that is evaluated before each iteration.

    // Example with user input
    string input = "";
    
    while (input != "exit")
    {
        //Do something
    
        input = Console.ReadLine();
    }
    
  • for Loop: The for loop is best used when the number of iterations is known beforehand.

    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine(i);
    }
    

20. What is a a abstract class

By : Muhammad Waseem Last edited : 18 Nov 2024 Level: Basic

A: An abstract class cannot be instantiated and is intended to be a base class for other classes. It can contain abstract methods (without implementation) and non-abstract methods (with implementation).

public abstract class Animal
{
    public abstract void MakeSound();
    
    public void Sleep()
    {
        Console.WriteLine("Sleeping...");
    }
}

21. What is a a sealed class

By : Muhammad Waseem Last edited : 18 Nov 2024 Level: Basic

A: A sealed class cannot be inherited. It is used to prevent other classes from inheriting from it.

public sealed class UserService { }

/*ERROR : CS0509 UserRolesService cannot 
          derive from sealed type UserService*/
public sealed class UserRolesService : Userservice {} 

22. What is a a partial class

By : Muhammad Waseem Last edited : 18 Nov 2024 Level: Basic

A: A partial class allows its definition to be split across multiple files. All parts are combined into a single class when the application is compiled.


public partial class Employee
{
    public Guid Id { get; set; }
    
    public Genders Gender { get; set; }
}

public partial class Employee
{
    public string Name { get; set; }
    
    public int Age { get; set; }
}

internal class Program
{
  static void Main(string[] args)
  {
     Employee emp = new Employee();

     // All properties could be accessed
     // Name, Age, Id, Gender
  }
}

23. What is a a generic class

By : Muhammad Waseem Last edited : 18 Nov 2024 Level: Basic

A: A generic class allows you to define a class with a placeholder for the type of its members. It provides type safety without compromising performance.

public class ApiResponseMessage<T>
{
    public int StatusCode { get; set; }

    public string Message { get; set; }

    public T Data { get; set; }

    public ApiResponseMessage(
      int statusCode, 
      string message, 
      T data)
    {
        StatusCode = statusCode;
        Message = message;
        Data = data;
    }

    public override string ToString()
    {
        return $"Status: {StatusCode}, Message: {Message}, Data: {Data}";
    }
}

24. What is a static class

By : Muhammad Waseem Last edited : 18 Nov 2024 Level: Basic

A: A static class cannot be instantiated and can only contain static members. It is used for grouping related static methods and properties.

public static class MathUtilities
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

25. What is abstraction

By : Muhammad Waseem Last edited : 19 Nov 2024 Level: Basic

A: Abstraction is a concept of OOP(Object Oriented Programming) that helps to hide complex details and show only the essential features of an object.

It allows us to focus on what an object does instead of how it does it (By hiding implementation)

For example, when you drive a car, you use the steering wheel, pedals, and buttons without needing to understand the intricate mechanics of the engine.

Abstraction is implemented through abstract classes.

26. What is encapsulation

By : Muhammad Waseem Last edited : 19 Nov 2024 Level: Basic

A: Encapsulation is a fundamental concept in Object-Oriented Programming (OOP) that restricts direct access to some of an object’s components and can prevent the accidental modification of data.

It allows the internal state of an object to be hidden from the outside, exposing only what is necessary through public methods.

For example, consider a class that represents a bank account. The balance of the account is kept private, and it can only be modified through methods like Deposit and Withdraw, ensuring that the balance cannot be changed directly from outside the class.

Encapsulation is achieved using the access modifiers (more specifically private)

27. Visibility of access modifiers

By : Muhammad Waseem Last edited : 19 Nov 2024 Level: Basic

A: Access modifiers are keywords in C# that define the visibility and accessibility of classes, methods, and other members.

Access modifers are a way, to implement encapsulation.The main access modifiers in C# are:

public: Accessible from any code in the same or referenced assembly.

private: Accessible only within the declaring class or struct; the most restrictive.

protected: Accessible within the class and by derived classes, allowing some inheritance.

internal: Accessible only within the same assembly, hiding details from other assemblies.

protected internal: Accessible from the current assembly or derived types, combining protected and internal access.

28. What is inheritance

By : Muhammad Waseem Last edited : 19 Nov 2024 Level: Basic

A: Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a class (derived class) to inherit properties and methods from another class (base class).

public class Animal
{
    public void Walk()
    {
        Console.WriteLine("Animal walks");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Dog barks");
    }
}

In the Program.cs:

Dog dog = new Dog();

dog.Walk(); // Inherited method

dog.Bark();  // Dog's own method

Inheritance promotes code reusability and establishes a relationship between classes (parent-child)

29. Different types of inheritance

By : Muhammad Waseem Last edited : 19 Nov 2024 Level: Basic

A: We have the following types of inheritance:

Single Inheritance: A class inherits from one base class.

public class Animal
{
    public void Speak()
    {
        Console.WriteLine("Animal speaks");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Dog barks");
    }
}

Multiple Inheritance: A class can inherit from multiple classes.

“C# does not support multiple inheritance directly, but it can be achieved using interfaces.”

public interface ICanBark
{
    void Bark();
}

public interface ICanRun
{
    void Run();
}

public class Dog : ICanBark, ICanRun
{
    public void Bark()
    {
        Console.WriteLine("Dog barks");
    }

    public void Run()
    {
        Console.WriteLine("Dog runs");
    }
}

Multilevel Inheritance: A class inherits from a derived class, forming a chain.

public class Car
{
    public void Start()
    {
        Console.WriteLine("Car is starting");
    }
}

public class SportsCar : Car
{
    public void Accelerate()
    {
        Console.WriteLine("Sports car is accelerating");
    }
}

public class RaceCar : SportsCar
{
    public void Race()
    {
        Console.WriteLine("Race car is racing");
    }
}

Hierarchical Inheritance: Multiple classes inherit from a single base class.

public class Animal
{
    public void Speak()
    {
        Console.WriteLine("Animal speaks");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Dog barks");
    }
}

public class Cat : Animal
{
    public void Meow()
    {
        Console.WriteLine("Cat meows");
    }
}

30. Can a class inherit from two classes in C#?

By : Muhammad Waseem Last edited : 20 Nov 2024 Level: Basic

A: In C#, a class cannot inherit from two classes due to the language’s support for single inheritance. This means that a class can only have one direct base class.

However, a class can implement multiple interfaces, which allows for a form of multiple inheritance.

31. What is the purpose of dependency injection

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Intermediate

A: The main purpose of Dependency Injection is to decouple the instantiation of a class from its dependencies. This makes it easier to manage and test the code, as dependencies can be swapped or mocked without changing the class itself.

32. What is dependency injection

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Intermediate

A: Dependency Injection (DI) is a design pattern used in .NET to achieve Inversion of Control (IoC) between classes and their dependencies. It allows for the creation of dependent objects outside of a class and provides those objects to a class through various means. This pattern helps in building loosely coupled, testable, and maintainable applications.

33. Different ways of registering dependency injection

By : Muhammad Waseem Last edited : 18 Nov 2024 Level: Intermediate

A: When registering services in the DI container, you can specify their lifetimes, which determine how and when instances are created and shared. The three main lifetimes are Scoped, Transient, and Singleton.

Scoped: A new instance of the service is created once per request or scope. This is useful for services that need to maintain state within a single request but should not share state across requests. In web applications, a new scope is created for each HTTP request.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<ICustomerService, CustomerService>();

Transient: A new instance of the service is created each time it is requested. This is ideal for lightweight, stateless services that do not hold any state between requests. Transient services can lead to higher memory consumption if not managed properly, as a new instance is created every time.

 var builder = WebApplication.CreateBuilder(args);
        
 builder.Services.AddTransient<ICustomerService, CustomerService>();

Singleton: A single instance of the service is created and shared throughout the application’s lifetime. This is suitable for services that maintain state or are expensive to create. Singleton services are created the first time they are requested or when the application starts, depending on the implementation.

var builder = WebApplication.CreateBuilder(args);
        
builder.Services.AddSingleton<ICustomerService, CustomerService>();

34. Different types of collections in .NET

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Intermediate

A: In .NET, collections are used to store, manage, and manipulate groups of related objects. There are several types of collections available, each with its own characteristics and use cases:

  • Array: An array is a fixed-size collection of elements of the same type. It provides fast access to elements by index but does not allow dynamic resizing.

    int[] numbers = new int[3] { 1, 2, 3 };
    
  • List: A List<T> is a generic collection that can dynamically resize. It provides methods to add, remove, and search for elements, making it more flexible than an array.

    List<int> numbers = new List<int> { 1, 2, 3 };
    numbers.Add(4);
    
  • Dictionary<TKey, TValue>: A dictionary is a collection of key-value pairs. It provides fast lookups by key and is useful for scenarios where you need to associate values with unique keys.

    Dictionary<string, int> ages = new Dictionary<string, int>();
    ages["Alice"] = 30;
    
  • Hashtable: A hashtable is a non-generic collection of key-value pairs. It is similar to a dictionary but does not enforce type safety and is generally slower due to boxing and unboxing operations.

    Hashtable hashtable = new Hashtable();
    hashtable["Alice"] = 30;
    
  • Queue: A queue is a first-in, first-out (FIFO) collection. It is useful for scenarios where you need to process elements in the order they were added.

    Queue<string> queue = new Queue<string>();
    queue.Enqueue("First");
    queue.Enqueue("Second");
    
  • Stack: A stack is a last-in, first-out (LIFO) collection. It is useful for scenarios where you need to process elements in reverse order.

    Stack<string> stack = new Stack<string>();
    stack.Push("First");
    stack.Push("Second");
    
  • HashSet: A HashSet<T> is a collection that contains unique elements and provides high-performance set operations. It is useful for scenarios where you need to ensure that all elements are distinct.

    HashSet<int> set = new HashSet<int> { 1, 2, 3 };
    set.Add(4);
    

These collections provide a range of functionalities to suit different programming needs, from simple arrays to more complex data structures like dictionaries, queues, and hashsets.

35. Difference between Configure and ConfigureServices

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Intermediate

A: In ASP.NET Core (3.1), Configure and ConfigureServices are two essential methods used in the startup class to set up the application.

ConfigureServices: This method is used to register application services. It is where you add services to the dependency injection container. For example, you can add MVC services, Entity Framework services, and other custom services that your application will use. This method is called first during the application startup.

Configure: This method is used to define the application’s request pipeline. It is where you specify how the application responds to HTTP requests. You can add middleware components, such as routing, authentication, and error handling, to the pipeline. This method is called after ConfigureServices.

These methods were removed in new versions coming after (.NET 3.1)

36. What is reflection and why we need it

By : Muhammad Waseem Last edited : 17 Nov 2024 Level: Intermediate

A: Reflection in C# allows you to inspect and manipulate types and members at runtime, facilitating the creation of instances, binding methods, and accessing properties dynamically.

It enables dynamic type creation for instances of unknown types at compile time, which is useful for plugins or external data sources.

Additionally, reflection supports late binding for invoking methods and accessing properties of unknown types, type inspection for examining metadata like attributes and methods, and simplifies serialization and deserialization by dynamically reading and writing object properties, enhancing efficiency in these processes. This is a brief overview of reflection.

37. Different types of dependency injection

By : Muhammad Waseem Last edited : 15 Nov 2024 Level: Intermediate

A: We have three types of dependencies injection in .NET :

  • Constructor Injection: Dependencies are provided through a class constructor.
  • Property Injection: Dependencies are assigned through public properties.
  • Method Injection: Dependencies are passed through methods.

38. What is delegate

By : Muhammad Waseem Last edited : 19 Nov 2024 Level: Intermediate

A: A delegate in C# is a type that represents references to methods with a specific parameter list and return type. It allows methods to be passed as parameters, enabling flexible and dynamic method invocation.

We can understand it with the following example:

internal class Program
{
    static void Main(string[] args)
    {
        Logger logger = LogInfo;

        logger.Invoke("Application started.");
    }

    public delegate void Logger(string message);

    public static void LogInfo(string message)
    {
        Console.WriteLine($"[INFO]: {message}");
    }
}

39. What is middleware in .NET

By : Muhammad Waseem Last edited : 16 Nov 2024 Level: Advanced

A: Middleware in .NET is a component that is used to handle requests and responses in an application pipeline. It is a crucial part of the ASP.NET Core framework, allowing developers to build modular and flexible web applications.

Middleware is often used to implement cross-cutting concerns such as authentication, logging, error handling, and caching. This allows these concerns to be handled in a centralized manner, improving code maintainability.

Following are the built in middlewares:

  • Static Files Middleware: Serves static files like HTML, CSS, and JavaScript.
  • Routing Middleware: Matches request URLs to the corresponding endpoints.
  • Authentication Middleware: Handles user authentication.
  • Authorization Middleware: Checks user permissions for accessing resources.
  • CORS Middleware: Configures Cross-Origin Resource Sharing policies.
  • Session Middleware: Manages user sessions.
  • Exception Handling Middleware: Catches and handles exceptions globally.