extension methods with Example Code

Extension methods with Example Code

What are extension methods?
Extension methods allow you to "add" methods to an existing class without modifying the original class. This helps keep your code organized and reusable.

 

How to use them?

Define a static class and a static method.

The first parameter of the method should use the this keyword to indicate which type you're extending.

 

Benefits:

You can extend functionality without modifying existing code.

They make the code more readable and reusable.

 

1. Extension Method for String Manipulation

Let's say we have a simple string type, and we want to add a method that checks if a string is a palindrome (a word that reads the same forward and backward).

Without Extension Method:

public class StringHelper

{

    public bool IsPalindrome(string input)

    {

        var reversed = new string(input.Reverse().ToArray());

        return input.Equals(reversed, StringComparison.OrdinalIgnoreCase);

    }

}

We use it like this:

StringHelper helper = new StringHelper();

bool result = helper.IsPalindrome("racecar");

Console.WriteLine(result);  // Output: True

 

With Extension Method:

Now, instead of creating a helper class, you can directly add this functionality to the string class using an extension method.

Create the Extension Method:

public static class StringExtensions

{

    public static bool IsPalindrome(this string input)

    {

        var reversed = new string(input.Reverse().ToArray());

        return input.Equals(reversed, StringComparison.OrdinalIgnoreCase);

    }

}

 

Usage:

Now, you can call IsPalindrome() directly on any string object.

string word = "racecar";

bool result = word.IsPalindrome();

Console.WriteLine(result);  // Output: True

Explanation:

this keyword in the extension method tells the compiler that we are extending the string type.

Now, you don't need an external class like StringHelper anymore.

 

2. Extension Method for Logging an Error

Imagine you have an ILogger that you use in various places, and you want to add a custom extension to log a "warning" message that includes a specific trace ID. This will make it reusable across multiple classes.

Without Extension Method:

public class ErrorLogger

{

    private readonly ILogger<ErrorLogger> _logger;

 

    public ErrorLogger(ILogger<ErrorLogger> logger)

    {

        _logger = logger;

    }

 

    public void LogErrorWithTraceId(string message, string traceId)

    {

        _logger.LogWarning($"Warning: {message} | TraceId: {traceId}");

    }

}

With Extension Method:

You can use an extension method to log the error with the trace ID more cleanly.

Create the Extension Method:

public static class LoggerExtensions

{

    public static void LogWarningWithTraceId(this ILogger logger, string message, string traceId)

    {

        logger.LogWarning($"Warning: {message} | TraceId: {traceId}");

    }

}

Usage:

Now, you can call the LogWarningWithTraceId() method directly on any ILogger object.

ILogger<ErrorLogger> logger = ...;  // Assume this is injected

string traceId = "abc-123";

logger.LogWarningWithTraceId("Something went wrong", traceId);

Explanation:

The LogWarningWithTraceId method is now available on any ILogger object, no matter where you use it, without having to modify the original ILogger interface or class.

 

3. Extension Method for Calculating the Area of a Circle

You can create an extension method for numeric types to calculate the area of a circle given the radius.

Without Extension Method:

public class CircleHelper

{

    public double CalculateArea(double radius)

    {

        return Math.PI * Math.Pow(radius, 2);

    }

}

With Extension Method:

Now, let's extend the double type with an AreaOfCircle() method.

Create the Extension Method:

public static class NumericExtensions

{

    public static double AreaOfCircle(this double radius)

    {

        return Math.PI * Math.Pow(radius, 2);

    }

}

Usage:

Now, you can call AreaOfCircle() directly on a double value.

double radius = 5.0;

double area = radius.AreaOfCircle();

Console.WriteLine($"Area of Circle: {area}");  // Output: Area of Circle: 78.53981633974483

Explanation:

The extension method AreaOfCircle is added to the double type, which calculates the area of a circle with the given radius.

This method is now available for all double values, making it easy to use in different parts of your code.

 

4. Extension Method to Format Dates

Suppose you need to format DateTime objects in a specific way (e.g., "yyyy-MM-dd").

Without Extension Method:

public class DateHelper

{

    public string FormatDate(DateTime date)

    {

        return date.ToString("yyyy-MM-dd");

    }

}

With Extension Method:

You can add this formatting directly to DateTime using an extension method.

Create the Extension Method:

public static class DateTimeExtensions

{

    public static string ToCustomFormat(this DateTime date)

    {

        return date.ToString("yyyy-MM-dd");

    }

}

Usage:

Now, you can call ToCustomFormat() directly on a DateTime object.

DateTime now = DateTime.Now;

string formattedDate = now.ToCustomFormat();

Console.WriteLine(formattedDate);  // Output: 2024-12-28 (or today's date)

Explanation:

The extension method ToCustomFormat allows you to format DateTime objects without needing to repeatedly call ToString("yyyy-MM-dd").

This is a clean and reusable way of extending functionality for DateTime.

 

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced