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

      C# : How can we access private method outside class

      Introduction In object-oriented programming, encapsulation is a fundamental principle that restricts direct access to the internal implementation details of a class. Private methods, being part of this internal implementation, are designed to be accessible only within the confines of the class they belong to. However, there might be scenarios where you need to access a private method from outside the class. In this blog post, we'll explore several techniques to achieve this in C#. 1. Reflection: A Powerful Yet Delicate Approach Reflection is a mechanism in C# that allows inspecting and interacting with metadata about types, fields, properties, and methods. While it provides a way to access private methods, it should be used cautiously due to its potential impact on maintainability and performance. using System ; using System . Reflection ; public class MyClass { private void PrivateMethod ( ) { Console . WriteLine ( "This is a private method."...

      20+ LINQ Concepts with .Net Code

      LINQ   (Language Integrated Query) is one of the most powerful features in .NET, providing a unified syntax to query collections, databases, XML, and other data sources. Below are 20+ important LINQ concepts, their explanations, and code snippets to help you understand their usage. 1.  Where  (Filtering) The  Where()  method is used to filter a collection based on a given condition. var numbers = new List < int > { 1 , 2 , 3 , 4 , 5 , 6 } ; var evenNumbers = numbers . Where ( n => n % 2 == 0 ) . ToList ( ) ; // Output: [2, 4, 6] C# Copy 2.  Select  (Projection) The  Select()  method projects each element of a sequence into a new form, allowing transformation of data. var employees = new List < Employee > { /* ... */ } ; var employeeNames = employees . Select ( e => e . Name ) . ToList ( ) ; // Output: List of employee names C# Copy 3.  OrderBy  (Sorting in Ascending Order) The  Or...

      C# : Understanding Types of Classes

      In C#, classes serve as the building blocks of object-oriented programming, providing a blueprint for creating objects. Understanding the types of classes and their applications is crucial for designing robust and maintainable software. In this blog, we’ll delve into various types of classes in C#, accompanied by real-world scenarios and code snippets for a practical understanding. 1. Regular (Instance) Classes Definition: Regular classes are the most common type and are used to create instances or objects. They can contain fields, properties, methods, and other members. Example Scenario: A Person class representing individual persons with properties like Name and Age. public class Person { public string Name { get ; set ; } public int Age { get ; set ; } } 2. Static Classes Definition: A static class cannot be instantiated and can only contain static members (methods, properties, fields). It’s often used for utility functions. Example Scenario: A MathUtility cla...