C# Interview Questions

36 Questions
C# Programming

C# Programming

Web DevelopmentFrontendBackendGame Dev

Question 14

What are extension methods in C#?

Answer:

Extension methods in C# are a way to add new methods to existing types without modifying the original type or creating a new derived type. They allow you to "extend" the functionality of existing classes or interfaces by defining static methods in a static class. These methods appear as if they are part of the original type, providing a seamless way to enhance its capabilities.

Key Features of Extension Methods

  1. Static Methods:

    • Extension methods are static methods defined in a static class.
  2. First Parameter:

    • The first parameter of an extension method specifies the type it extends, and it is preceded by the this keyword.
  3. IntelliSense Support:

    • Once an extension method is defined, it shows up in IntelliSense as if it were a method of the extended type.
  4. No Modification Required:

    • The original type is not modified, ensuring that the extension does not affect the existing codebase or violate encapsulation principles.

Defining and Using Extension Methods

Step-by-Step Example

  1. Define a Static Class:

    • Create a static class to contain the extension methods.
  2. Define a Static Method:

    • Define a static method within the static class, with the first parameter specifying the type to extend, preceded by the this keyword.

Example

Here's an example of an extension method that adds a WordCount method to the string type:

using System;

public static class StringExtensions
{
    // Extension method to count the number of words in a string
    public static int WordCount(this string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return 0;
        }

        // Split the string into words using whitespace as the delimiter
        string[] words = str.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        return words.Length;
    }
}

public class Program
{
    public static void Main()
    {
        string sentence = "Hello, how are you doing today?";
        
        // Use the extension method as if it were a method of the string class
        int count = sentence.WordCount();

        Console.WriteLine($"The sentence has {count} words.");
    }
}

In this example:

  • StringExtensions is a static class containing the extension method.
  • WordCount is defined as a static method that extends the string type.
  • The this keyword before the string str parameter indicates that WordCount extends the string type.
  • The WordCount method splits the string into words and returns the count.
  • In Main, the WordCount method is used as if it were a built-in method of the string class.

More Complex Example

Here’s a more complex example where we add an extension method to a custom type:

using System;

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public static class PersonExtensions
{
    // Extension method to get the full name of a Person
    public static string GetFullName(this Person person)
    {
        return $"{person.FirstName} {person.LastName}";
    }
}

public class Program
{
    public static void Main()
    {
        Person person = new Person { FirstName = "John", LastName = "Doe" };

        // Use the extension method as if it were a method of the Person class
        string fullName = person.GetFullName();

        Console.WriteLine($"Full Name: {fullName}");
    }
}

In this example:

  • PersonExtensions is a static class containing the extension method.
  • GetFullName is an extension method for the Person class.
  • The GetFullName method concatenates the FirstName and LastName properties of a Person object.
  • In Main, the GetFullName method is used as if it were a method of the Person class.

Benefits of Extension Methods

  1. Enhancing Existing Types:

    • Add methods to existing types without modifying their source code or using inheritance.
  2. Code Readability:

    • Improve code readability by allowing methods to be called on objects directly, making the code more intuitive.
  3. Maintainability:

    • Provide a way to organize helper methods logically and maintainably without cluttering the original type with additional methods.
  4. Reusability:

    • Promote code reusability by creating methods that can be used across different projects and solutions.

Summary

Extension methods in C# provide a powerful and flexible way to enhance existing types with new functionality without altering their original implementation. By defining static methods in static classes and using the this keyword, developers can add new methods to any type, improving code readability, maintainability, and reusability.

Recent job openings