c# interview Q

 

private constructor

A private constructor in C# is a special instance constructor that is inaccessible outside the class itself. Its primary uses are to prevent a class from being instantiated by other classes and to enforce the singleton design pattern

Primary Use Cases

1. Singleton Design Pattern

The most common use of a private constructor is in implementing the singleton pattern, which ensures that only one instance of a class exists throughout the application's lifecycle and provides a global point of access to that instance

Real-World Example:

ConfigurationManager or DatabaseConnectionPool class in an application needs to maintain a single, consistent state and be accessible globally.

public sealed class ConfigurationManager
{
    // A single instance of the class, initialized lazily.
    private static readonly ConfigurationManager instance = new ConfigurationManager();
    public string ConfigSetting { get; private set; }

    // The private constructor prevents direct instantiation.
    private ConfigurationManager()
    {
        // Load configuration settings from a file or database here.
        ConfigSetting = "Database Connection String: Server=localhost;...";
        Console.WriteLine("Configuration Manager instance created.");
    }

    // A public static method to access the single instance.
    public static ConfigurationManager Instance
    {
        get { return instance; }
    }
}
// Usage in another class:
// ConfigurationManager manager = new ConfigurationManager(); // Error: Cannot access private constructor
// string connection = ConfigurationManager.Instance.ConfigSetting; // Correct way to access

2. Classes with Only Static Members

If a class contains only static methods and properties, and you want to prevent developers from accidentally creating an instance of that class, a private constructor is used. The compiler will not generate a default public constructor in this case .

Real-World Example:

UtilityHelper class with helper functions for mathematical operations or string manipulation.

public static class UtilityHelper
{
    // A private constructor prevents instantiation.
    private UtilityHelper() { }

    public static string FormatName(string firstName, string lastName)
    {
        return $"{firstName} {lastName}";
    }

    public static double CalculateArea(double radius)
    {
        return Math.PI * radius * radius;
    }
}

// Usage:
// UtilityHelper helper = new UtilityHelper(); // Error: Cannot access private constructor
// string name = UtilityHelper.FormatName("John", "Doe"); // Correct

3. Controlled Object Creation (Factory Pattern Variation)

Sometimes you want to force object creation to occur only through a static factory method within the class itself, which can perform complex initialization or use a pool of objects. The private constructor ensures this control.

how do you handle exceptions in web api

Exception handling in web APIs typically involves a combination of local error management and centralized, global mechanisms to ensure consistent, meaningful responses to clients and robust application behavior.

The main approaches (primarily in the context of ASP.NET Web API) include:

1. Local Handling (Try-Catch Blocks)

The most basic method is using try-catch blocks within your code, service layers, or controller actions to manage anticipated errors, such as database connectivity issues or invalid input.

Purpose: To recover from errors or perform cleanup operations (e.g., releasing resources using finally blocks or using statements).

Response: Within the catch block, you can return a specific HTTP status code and a meaningful, structured error payload (e.g., using IHttpActionResult methods like NotFound(), BadRequest(ModelState), or InternalServerError(ex) in older ASP.NET Web API, or returning a ProblemDetails object in ASP.NET Core).

Best Practice: Use try-catch when you can handle the exception and return a specific, appropriate HTTP status code (e.g., 400 Bad Request for validation errors, 404 Not Found for missing resources).

2. Exception Filters

Exception filters are attributes that catch unhandled exceptions at the action or controller level.

Purpose: They provide a centralized way to handle specific types of exceptions for a group of actions or an entire controller without cluttering every method with try-catch blocks.

Implementation: You create a custom filter by deriving from ExceptionFilterAttribute and overriding the OnException method.

Scope: They can be applied to a specific action method, an entire controller, or globally to all controllers in the application.

Limitation: They do not catch exceptions that occur outside of the controller action context, such as exceptions in message handlers, controller constructors, or during routing/serialization.

3. Global Exception Handlers (Middleware)

For application-wide, consistent error management, global handlers (often implemented as middleware in modern ASP.NET Core) are the recommended approach.

Purpose: To catch all unhandled exceptions anywhere in the application's pipeline and return a generic, consistent error response (typically a 500 Internal Server Error) while logging the detailed exception on the server side for diagnostics.

Implementation:

  • ASP.NET Core: You can use the built-in UseExceptionHandler middleware in Program.cs or implement the IExceptionHandler interface (recommended in .NET 8+).

Older Web API 2: This involved replacing the default IExceptionHandler service with a custom implementation in the WebApiConfig.

Best Practice: This mechanism prevents sensitive server details or unhandled exception stack traces from being exposed to the client, providing a clean, consistent error format.

Key Best Practices

  • Use Appropriate HTTP Status Codes: Return meaningful status codes (e.g., 400, 401, 403, 404, 500) rather than a generic 200 OK with an error message in the body.

  • Return Consistent Error Responses: Define a standard structure for error payloads across your API (e.g., using the Problem Details for HTTP APIs standard).

  • Log Exceptions: Ensure all unhandled exceptions are properly logged with relevant details (trace ID, machine name, etc.) on the server side for debugging purposes, but avoid leaking sensitive data to the client.

  • Avoid Exception-Based Control Flow: Don't use exceptions for expected or common business logic validations; use conditional checks instead.

we use middleware and filter both in web api what is the difference and their use case

Middleware and filters in a web API are both used to process requests and responses but operate at different layers of the application stack, serving distinct use cases

Middleware

Middleware sits in the request processing pipeline and is executed sequentially for every request, irrespective of the specific endpoint that will handle it

Operation: Each middleware component can perform logic before or after calling the next component in the pipeline, allowing it to short-circuit the pipeline entirely if necessary (e.g., in the case of authentication failure or static file serving) [1].

Use Cases: Middleware is ideal for cross-cutting concerns that apply globally to the entire application:

Authentication and Authorization: Verifying credentials and permissions early in the pipeline Logging and Tracing: Logging details about every incoming request and outgoing response

Static File Serving: Directly serving static files (HTML, CSS, images) without involving API controllers

Error Handling: Catching exceptions thrown by subsequent components in the pipeline [3].

Filters

Filters are targeted at specific parts of the MVC/API execution lifecycle and are executed only when the request reaches the controller/action level [1, 4]. They provide a way to inject logic just before or after specific actions, or around model binding and result execution.

Operation: Unlike middleware, filters are typically associated with controllers or actions through attributes or configuration, and they do not process the raw HTTP request/response stream directly [1, 4]. They have access to the context of the action being executed, including route data, model state, and the action's arguments/result [1].

Use Cases: Filters are best suited for functionality specific to the API's business logic or action execution:

Model Validation: Checking if the data sent to a specific action is valid using ModelState.

Action-Specific Authorization: Restricting access to a particular controller (e.g., only Admin users can access AdminController).

Response Shaping: Using ResultFilters to wrap the data returned by an action into a specific JSON structure.

Caching: Applying specific caching rules to certain data-heavy endpoints (e.g., GetProductList).

Resource Filters: Wrapping the action execution but after authorization, enabling logic such as response caching for specific endpoints [4].

Authorization Filters: A more specific form of authorization check that can be applied to individual actions or controllers

Key Differences

FeatureMiddlewareFilters
ScopeGlobal: Runs for every request (including static files like images).Targeted: Specific to MVC/API controllers or actions.
ContextLow-level access to HttpContext only.Rich access to MVC context (ModelState, IActionResults, action arguments).
TimingRuns before routing is determined.Runs after a route is matched to a controller/action.
FrameworkIndependent of MVC; works for any HTTP request.Tightly integrated with the MVC/API controller framework.

what is generic and non generic in c#

In C#, the primary difference between generic and non-generic types lies in type safetyperformance, and code reusability

Key Differences

FeatureGenericNon-Generic
Type SafetyStrongly typed; type mismatches are caught at compile-time.Not type-safe; stores data as object, leading to potential runtime errors.
PerformanceBetter performance; avoids the overhead of boxing (converting value types to objects) and unboxing (converting objects back to value types).Slower due to required boxing/unboxing operations for value types.
CastingNo explicit casting required when retrieving elements.Requires explicit casting when retrieving elements.
Code ReusabilityHighly reusable; a single generic definition works with multiple data types.Less reusable; often requires writing separate logic or handling for different types if type-specific behavior is needed.
NamespaceFound in System.Collections.Generic namespace (e.g., List<T>).Found in System.Collections namespace (e.g., ArrayList).

Examples

The most common examples involve collections:

Generic List: List<int> myList = new List<int>(); stores only integers. Adding a string would result in a compile-time error. eg: Dictionary<TKey, TValue> :Stores key-value pairs of specific types Stack and Queue: Specific versions of LIFO and FIFO collections.

Non-generic ArrayList: ArrayList myList = new ArrayList(); can store integers, strings, or any other objects in the same collection. Retrieving items requires casting and risks a runtime error if the cast is incorrect. eg: Hashtable: The non-generic version of a Dictionary. Queue and Stack: Basic versions that don't enforce a single type.

what is claim in jwt

a claim is a piece of information asserted about a subject (typically a user) or the token itself

Comments

  1. dependency injection c# and their type with example

    ReplyDelete

Post a Comment

Popular posts from this blog