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

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

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