Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My first extension method, could it be written better?

Tags:

Because this is my first attempt at an extension method that seems quite useful to me, I just want to make sure I'm going down the right route

 public static bool EqualsAny(this string s, string[] tokens, StringComparison comparisonType)
    {
        foreach (string token in tokens)
        {
            if (s.Equals(token, comparisonType))
            {
                return true;
            }
        }

        return false;
    }

Called by

if (queryString["secure"].EqualsAny(new string[] {"true","1"}, StringComparison.InvariantCultureIgnoreCase))
{
    parameters.Protocol = Protocol.https;
}

EDIT: Some excellent suggestions coming through, exactly the sort of thing I was looking for. Thanks

EDIT:

I have decided on the following implementation

public static bool EqualsAny(this string s, StringComparison comparisonType, params string[] tokens)
{
    // for the scenario it is more suitable for the code to continue
    if (s == null) return false;

    return tokens.Any(x => s.Equals(x, comparisonType));
}

public static bool EqualsAny(this string s, params string[] tokens)
{
    return EqualsAny(s, StringComparison.OrdinalIgnoreCase, tokens);
}

I preferred using params over IEnumerable because it simplified the calling code

if (queryString["secure"].EqualsAny("true","1"))
{
    parameters.Protocol = Protocol.https;
}

A far cry on the previous

if (queryString["secure"] != null)
{
    if (queryString["secure"] == "true" || queryString["secure"] == "1")
    {
        parameters.Protocal = Protocal.https;
    }
}

Thank you again!

like image 642
Nick Allen Avatar asked May 22 '09 12:05

Nick Allen


People also ask

What is an advantage of using extension methods?

The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.

Are extension methods good?

For an application programmer, extension methods are an incredibly powerful and expressive tool. They enable convenience, extensibility, and an improved intellisence experience. However, many of the features that make extension methods so useful for library consumers can be problematic for class library authors.

What is the difference between a static method and an extension method?

The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.

When should we use extension methods in C#?

Use extension method which would help you to add a method to existing types without modifying the original source code and without the use of inheritance. Use 'this' keyword in extension method parameter so that it refer to OriginalClass class when you invoke it in Program class.


1 Answers

Yes! First, you need to check s for null. Also, let it accept any IEnumerable<string> for tokens rather than just an array, and then use other linq operators to do the check:

public static bool EqualsAny(this string s, IEnumerable<string> tokens, StringComparison comparisonType)
{
    if (s== null) return false;
    return tokens.Any(t => s.Equals(t, comparisonType));
}

Thinking about how to handle a null value for s, there's a third option no one's used yet:

 public static bool EqualsAny(this string s, IEnumerable<string> tokens, StringComparison comparisonType)
{
    if (s== null) return tokens.Any(t => t == null);
    return tokens.Any(t => s.Equals(t, comparisonType));
}

Finally, regarding your chosen implementation: if you're going to have overloads, you might as well have IEnumerable overloads as well, and have your params code call those.

like image 93
Joel Coehoorn Avatar answered Jan 01 '23 21:01

Joel Coehoorn