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

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

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

C# : 12.0 : Primary constructor

Introduction In C# 12.0, the introduction of the "Primary Constructor" simplifies the constructor declaration process. Before delving into this concept, let's revisit constructors. A constructor is a special method in a class with the same name as the class itself. It's possible to have multiple constructors through a technique called constructor overloading.  By default, if no constructors are explicitly defined, the C# compiler generates a default constructor for each class. Now, in C# 12.0, the term "Primary Constructor" refers to a more streamlined way of declaring constructors. This feature enhances the clarity and conciseness of constructor declarations in C# code. Lets see an simple example code, which will be known to everyone. public class Version { private int _value ; private string _name ; public Version ( int value , string name ) { _name = name ; _value = value ; } public string Ve