C# Interview Questions
C# Programming
Web DevelopmentFrontendBackendGame DevQuestion 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
-
Static Methods:
- Extension methods are static methods defined in a static class.
-
First Parameter:
- The first parameter of an extension method specifies the type it extends, and it is preceded by the
thiskeyword.
- The first parameter of an extension method specifies the type it extends, and it is preceded by the
-
IntelliSense Support:
- Once an extension method is defined, it shows up in IntelliSense as if it were a method of the extended type.
-
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
-
Define a Static Class:
- Create a static class to contain the extension methods.
-
Define a Static Method:
- Define a static method within the static class, with the first parameter specifying the type to extend, preceded by the
thiskeyword.
- Define a static method within the static class, with the first parameter specifying the type to extend, preceded by the
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:
StringExtensionsis a static class containing the extension method.WordCountis defined as a static method that extends thestringtype.- The
thiskeyword before thestring strparameter indicates thatWordCountextends thestringtype. - The
WordCountmethod splits the string into words and returns the count. - In
Main, theWordCountmethod is used as if it were a built-in method of thestringclass.
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:
PersonExtensionsis a static class containing the extension method.GetFullNameis an extension method for thePersonclass.- The
GetFullNamemethod concatenates theFirstNameandLastNameproperties of aPersonobject. - In
Main, theGetFullNamemethod is used as if it were a method of thePersonclass.
Benefits of Extension Methods
-
Enhancing Existing Types:
- Add methods to existing types without modifying their source code or using inheritance.
-
Code Readability:
- Improve code readability by allowing methods to be called on objects directly, making the code more intuitive.
-
Maintainability:
- Provide a way to organize helper methods logically and maintainably without cluttering the original type with additional methods.
-
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.