All posts by Manish Gupta

Reverse Word in C#

public static void Main(string[] args)
{
Console.WriteLine(“Enter the Word:”);
string s = Console.ReadLine();
string[] a = s.Split(‘ ‘);
Array.Reverse(a);
Console.WriteLine(“Reverse Word is:”);
for(int i = 0; i <= a.Length – 1; i++)
{
Console.Write(a[i]+””+’ ‘);
}
Console.ReadKey();
}

Difference between Rest and Restful API

The terms REST and RESTful API are related but distinct:

  1. REST (Representational State Transfer)
  • It is an architectural style that defines a set of constraints for designing networked applications.
  • REST is not a protocol or a standard but a set of principles that guide API design.
  • It emphasizes stateless communication, resource-based interactions, and the use of standard HTTP methods (GET, POST, PUT, DELETE).
  • REST-compliant systems should follow constraints like client-server architecture, statelessness, cacheability, uniform interface, layered system, and optional code on demand.

2. RESTful API (RESTful Web Service)

    • A RESTful API is an implementation of the REST architecture in a web service.
    • It follows REST principles and allows clients to interact with resources using HTTP methods.
    • It typically uses JSON or XML for data exchange.
    • A properly designed RESTful API should provide meaningful URIs, standard HTTP status codes, and proper request/response formats.

    Key Differences

    FeatureRESTRESTful API
    DefinitionArchitectural styleWeb service following REST principles
    Standard?No, just a set of guidelinesYes, it implements REST principles
    CommunicationConceptual, defines how APIs should workPractical, an actual API built using REST
    ImplementationCannot be implemented directlyImplemented using HTTP, JSON, XML, etc.

    Example:
    A RESTful API for a library system:

    • GET /books → Retrieve all books
    • POST /books → Add a new book
    • GET /books/1 → Retrieve book with ID 1
    • PUT /books/1 → Update book with ID 1
    • DELETE /books/1 → Delete book with ID 1

    In summary, REST is a concept, while a RESTful API is an actual implementation of that concept in web services.

    Difference between ref and out

    In C#, ref and out are both used to pass arguments by reference to a method, allowing the method to modify the original variable. However, they have key differences in terms of initialization and usage.

    1. ref (Pass by Reference with Initialization Required)
    • The caller must initialize the variable before passing it to the method.
    • The method can modify the variable.
    • The variable retains the modified value after the method call.

    Example of ref

    ✅ value is initialized before passing it to ModifyValue.
    ✅ ref allows modifying value inside the method.

    1. out (Pass by Reference without Initialization)
    • The caller does not need to initialize the variable.
    • The method must assign a value to the variable before returning.
    • Used mainly for returning multiple outputs from a method.

    Example of out

    ✅ resultSum and resultProduct don’t need initialization before calling GetSumAndProduct.
    ✅ The method must assign values to sum and product before returning.

    Key Differences Between ref and out

    Featurerefout
    Initialization before passing?Yes, must be initialized before method callNo, doesn’t need to be initialized
    Modification inside method?Optional, method may modify the valueMandatory, method must assign a value before returning
    Use caseModifying an existing variableReturning multiple values from a method

    When to Use?

    • Use ref when a method modifies an existing value.
    • Use out when a method returns multiple values.

    Using Both ref and out in the Same Method

    Let’s create an example where:

    • ref is used to update an existing value.
    • out is used to return multiple new values.

    Example: Updating and Returning Multiple Values

    Explanation:

    1. ref int number
    • The input value num (initialized as 3) is passed by reference.
    • It is modified inside ProcessNumbers (num += 5, making it 8).
    1. out int square, out int cube
    • These variables do not need to be initialized before calling ProcessNumbers.
    • The method must assign values to square and cube before returning.

    Final Output:

    Updated Number: 8
    Square: 64
    Cube: 512

    Key Takeaways:

    • ref is used when you need to update an existing variable inside the method.
    • out is used when you need to return multiple values without requiring initialization.

    Difference between async and await

    In asynchronous programming, async and await are used to handle asynchronous operations more effectively. Here’s the difference:

    1. async (Asynchronous Function)
    • The async keyword is used to declare a function as asynchronous.
    • An async function always returns a Promise implicitly, even if it contains synchronous code.
    • Inside an async function, you can use await to pause execution until a Promise is resolved or rejected.

    Example:

    Even though fetchData returns a string, it is automatically wrapped in a Promise.

    1. await (Pausing Execution Until a Promise Resolves)
    • The await keyword can only be used inside an async function.
    • It pauses the execution of the function until the Promise resolves, making the code look synchronous.
    • It simplifies working with Promises by eliminating .then() chaining.

    Example:

    Here, the function waits for the setTimeout to complete before logging the result.

    Key Differences:

    Featureasyncawait
    DefinitionDeclares an asynchronous functionPauses execution until a Promise resolves
    ReturnsAlways returns a PromiseReturns the resolved value of a Promise
    UsageBefore a function declarationInside an async function only
    BehaviorMakes a function asynchronousWaits for async operations to complete

    Real-World Example: Fetching API Data using async and await

    Let’s say we need to fetch user data from an API. Without async/await, we would use .then(), making the code slightly harder to read. Using async/await makes it cleaner and more readable.

    Example: Fetching User Data

    Without async/await (Using .then())

    • This code fetches user data and logs it.
    • But the .then() chain makes it a bit harder to read, especially if multiple asynchronous calls are needed.

    With async/await (Cleaner & More Readable)

    How This Works:

    1. fetch() returns a Promise, which await waits to resolve.
    2. response.json() is also a Promise, so await waits again.
    3. The try…catch block handles errors gracefully.

    When to Use async/await?

    ✅ When working with APIs (like fetching data).
    ✅ When dealing with database queries.
    ✅ When handling file I/O operations.
    ✅ When writing event-driven code in JavaScript.

    Difference between readonly and const keyword in C#

    In C#, readonly and const are both used to define immutable values, but they have key differences in how and when their values are assigned.

    1. const (Constant)
    • A const field is a compile-time constant, meaning its value must be assigned at declaration and cannot be changed later.
    • It is implicitly static, so it belongs to the type rather than an instance.
    • The value of a const field is hardcoded into the compiled code, so changes require recompilation.
    • Only primitive types, enums, and string can be const.

    Example of const:

    Example. Pi is a compile-time constant and cannot be changed.

    1. readonly (Read-Only Field)
    • A readonly field can be assigned only during declaration or in the constructor, making it a runtime constant.
    • It is not implicitly static, so each instance can have different values.
    • Unlike const, readonly fields can hold reference types and mutable objects (though the reference itself remains immutable).
    • It is evaluated at runtime, meaning it can be set dynamically based on constructor parameters.

    Example of readonly:

    Each instance of Example can have a different number value.

    Key Differences:

    Featureconstreadonly
    AssignmentOnly at declarationAt declaration or in constructor
    MutabilityCannot change after compilationCan be assigned per instance in the constructor
    StorageStored as a literal in compiled codeStored in memory like normal fields
    Type SupportOnly primitive types, enums, and stringsAny data type (value or reference)
    Instance vs. StaticAlways staticCan be instance or static
    Runtime EvaluationNo (compile-time only)Yes (runtime assignment allowed)

    When to Use Which?

    • Use const when the value is truly constant (e.g., mathematical constants like Pi, conversion factors).
    • Use readonly when the value can be determined at runtime (e.g., configuration settings, object references).

    Dependency Injection (DI) in C#

    Dependency Injection (DI) is a design pattern used in C# (and other programming languages) to achieve loose coupling between objects and their dependencies. It allows an object to receive its dependencies from an external source rather than creating them internally.

    Why Use Dependency Injection?
    1. Loose Coupling – Reduces dependencies between objects, making the system more maintainable.
    2. Improved Testability – Dependencies can be mocked easily for unit testing.
    3. Better Code Reusability – Components are more modular and reusable.
    4. Easier to Manage Dependencies – Centralized management of dependencies.

    How Dependency Injection Works in C#?

    In C#, DI is commonly implemented using the built-in dependency injection container (IServiceCollection and IServiceProvider) available in ASP.NET Core.

    Types of Dependency Injection
    1. Constructor Injection (Most common)
    2. Property Injection
    3. Method Injection

    Example: Implementing Constructor Injection in C#

    Step 1: Create an Interface

    public interface IMessageService
    {
       void SendMessage(string message);
    }

    Step 2: Implement the Interface

    public class EmailService : IMessageService
    {
       public void SendMessage(string message)
       {
           Console.WriteLine($”Email sent: {message}”);
       }
    }

    Step 3: Inject Dependency via Constructor

    public class Notification
    {
       private readonly IMessageService _messageService;

       public Notification(IMessageService messageService)
       {
           _messageService = messageService;
       }

       public void Notify(string message)
       {
           _messageService.SendMessage(message);
       }
    }

    Step 4: Configure Dependency Injection in ASP.NET Core

    var serviceProvider = new ServiceCollection()
       .AddSingleton<IMessageService, EmailService>() // Register dependency
       .BuildServiceProvider();

    var notification = new Notification(serviceProvider.GetService<IMessageService>());
    notification.Notify(“Hello, Dependency Injection!”);

    Built-in Dependency Injection in ASP.NET Core

    In ASP.NET Core, you register dependencies in Program.cs:

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddSingleton<IMessageService, EmailService>(); // Register DI

    var app = builder.Build();
    app.Run();

    Then, in a Controller:

    public class HomeController : Controller
    {
       private readonly IMessageService _messageService;

       public HomeController(IMessageService messageService)
       {
           _messageService = messageService;
       }

       public IActionResult Index()
       {
           _messageService.SendMessage(“Hello from Controller!”);
           return View();
       }
    }

    Conclusion

    Dependency Injection is a powerful pattern that makes C# applications more modular, maintainable, and testable. It is widely used in ASP.NET Core applications for managing dependencies efficiently.