Skip to main content

C# : Interview questions (31-35)


  Questions :

      • How do you handle null reference exceptions in C#?
      • Explain the concept of delegates in C#.
      • What is a multicast delegate?
      • What is an event in C#?
      • Explain the difference between events and delegates.

      Answers :

      Handling Null Reference Exceptions in C#:

      Null Reference Exceptions occur when you try to access a member or method of an object that is null. To handle these exceptions, you can use conditional statements to check for null values before accessing members or methods, or you can use the null-conditional operator (?.) introduced in C# 6.0.

      // Using conditional statements
      if (obj != null) 
      {
          obj.Method();
      }
      
      // Using null-conditional operator
      obj?.Method();
      

      In both cases, the method Method() is only called if obj is not null, preventing a Null Reference Exception.

      Delegates in C#:

      Delegates in C# are reference types that hold references to methods, allowing methods to be passed as arguments to other methods or stored as data. They enable a form of function pointer or callback mechanism, facilitating encapsulation and loose coupling in applications.

      delegate void MyDelegate(string message);
      
      class Program 
      {
          static void Main() 
          {
              MyDelegate delegateObj = new MyDelegate(PrintMessage);
              delegateObj("Hello, World!");
          }
      
          static void PrintMessage(string message) 
          {
              Console.WriteLine(message);
          }
      }
      

      In this example, MyDelegate is a delegate type that can hold references to methods with a signature matching void methodName(string). The delegate is instantiated with the PrintMessage method and invoked with a message string.

      Multicast Delegate:

      A multicast delegate in C# is a delegate that holds references to multiple methods. When invoked, a multicast delegate invokes all the methods it holds in the order they were added. Multicast delegates are commonly used in event handling scenarios.

      delegate void MyDelegate();
      
      class Program 
      {
          static void Main() 
          {
              MyDelegate delegateObj = Method1;
              delegateObj += Method2;
              delegateObj();
          }
      
          static void Method1() 
          {
              Console.WriteLine("Method 1");
          }
      
          static void Method2() 
          {
              Console.WriteLine("Method 2");
          }
      }
      

      In this example, delegateObj is a multicast delegate that holds references to both Method1 and Method2. When invoked, it calls both methods sequentially.

      Event in C#:

      An event in C# is a language construct that allows a class to provide notifications to other classes when certain actions occur. Events are based on delegates and follow the publisher-subscriber pattern, where one class (the publisher) raises events and other classes (subscribers) handle them.

      class Button 
      {
          public event EventHandler Click;
      
          public void OnClick() 
          {
              Click?.Invoke(this, EventArgs.Empty);
          }
      }
      

      In this example, the Click event is declared in the Button class. Subscribers can attach event handlers to the Click event and be notified when the button is clicked by calling the OnClick method.

      Difference between Events and Delegates:

      • Delegates: Delegates are types that hold references to methods. They enable method invocation through delegate instances.
      • Events: Events are a higher-level language construct built on top of delegates. They provide a standardized way for classes to provide notifications of state changes or actions to other classes without exposing their internal implementation.

      In summary, delegates are the building blocks for events, while events provide a more structured and encapsulated way to implement the observer pattern in C#.

      C# : Interview questions (36-40)

      Comments

      Popular posts from this blog

      Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

      RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

      Clean Architecture: What It Is and How It Differs from Microservices

      In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

      How Does My .NET Core Application Build Once and Run Everywhere?

      One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...