Skip to main content

C# : Interview questions (61-65)


Questions :

  • How do you implement method overloading in C#?
  • Explain the concept of extension methods.
  • What is a partial class in C#?
  • How do you implement operator overloading in C#?
  • What is the purpose of the "params" keyword in C#?
Answers :

1. Implementing Method Overloading in C#:

Method overloading in C# allows you to define multiple methods with the same name but different parameters (number, type, or both). The correct method to be invoked is determined by the arguments passed during the method call

public class MathOperations
{
    // Method to add two integers
    public int Add(int a, int b)
    {
        return a + b;
    }

    // Overloaded method to add three integers
    public int Add(int a, int b, int c)
    {
        return a + b + c;
    }

    // Overloaded method to add two doubles
    public double Add(double a, double b)
    {
        return a + b;
    }
}

In this example, the Add method is overloaded to handle different numbers and types of parameters.

2. Concept of Extension Methods:

Extension methods in C# allow you to add new methods to existing types without modifying the original type or creating a new derived type. Extension methods are static methods defined in static classes and are called as if they were instance methods on the extended type

public static class StringExtensions
{
    public static int WordCount(this string str)
    {
        return str.Split(new[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

// Usage
string phrase = "Hello world!";
int count = phrase.WordCount(); // Calling the extension method
Console.WriteLine(count); // Output: 2

In this example, the WordCount method is an extension method for the string type, allowing you to call it on any string instance.

3. Partial Class in C#:

A partial class in C# allows you to split the implementation of a class into multiple files. This is useful for organizing code, especially when working with large classes or auto-generated code. All parts of a partial class must be combined into a single class when the program is compiled.

// File1.cs
public partial class MyClass
{
    public void Method1()
    {
        Console.WriteLine("Method1");
    }
}

// File2.cs
public partial class MyClass
{
    public void Method2()
    {
        Console.WriteLine("Method2");
    }
}

// Usage
MyClass myClass = new MyClass();
myClass.Method1(); // Output: Method1
myClass.Method2(); // Output: Method2

In this example, the MyClass class is split into two files, each containing part of its implementation.

4. Implementing Operator Overloading in C#:

Operator overloading in C# allows you to redefine the behavior of operators for user-defined types (classes or structs). This is done by defining static methods in the type with the operator keyword.

public class Complex
{
    public double Real { get; }
    public double Imaginary { get; }

    public Complex(double real, double imaginary)
    {
        Real = real;
        Imaginary = imaginary;
    }

    // Overloading the + operator
    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }

    // Overloading the - operator
    public static Complex operator -(Complex c1, Complex c2)
    {
        return new Complex(c1.Real - c2.Real, c1.Imaginary - c2.Imaginary);
    }
}

// Usage
Complex c1 = new Complex(1.0, 2.0);
Complex c2 = new Complex(3.0, 4.0);
Complex c3 = c1 + c2; // Using the overloaded + operator
Console.WriteLine($"c3: {c3.Real} + {c3.Imaginary}i"); // Output: c3: 4.0 + 6.0i

5. Purpose of the "params" Keyword in C#:

The params keyword in C# allows you to pass a variable number of arguments to a method. It enables a method to accept a comma-separated list of arguments or an array of a specified type.

public class Calculator
{
    public int Add(params int[] numbers)
    {
        int sum = 0;
        foreach (int number in numbers)
        {
            sum += number;
        }
        return sum;
    }
}

// Usage
Calculator calculator = new Calculator();
int result1 = calculator.Add(1, 2, 3); // Output: 6
int result2 = calculator.Add(4, 5, 6, 7); // Output: 22
Console.WriteLine(result1); // Output: 6
Console.WriteLine(result2); // Output: 22
In this example, the Add method uses the params keyword to accept a variable number of integer arguments and calculate their sum.

Comments

Popular posts from this blog

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...

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...

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...