Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Access My Extension Method

Looking for a way to check if an string contains in another ignoring upper/lower case, I found it:

Works fine. Then, I tried put it to my StringExtensions namespace.

namespace StringExtensions
{

    public static class StringExtensionsClass
    {
        //... 

        public static bool Contains(this string target, string toCheck, StringComparison comp)
        {
            return target.IndexOf(toCheck, comp) >= 0;
        }
    }
}

and then:

using StringExtensions;

...

if (".. a".Contains("A", StringComparison.OrdinalIgnoreCase))

but I get the following error:

No overload for method 'Contains' takes '2' arguments

How do I fix it?

like image 295
Jack Avatar asked Dec 01 '11 17:12

Jack


People also ask

How do you extend a method in C#?

Select File > New > Project and select Visual C# and Console Application as shown below. Add the reference of the previously created class library to this project. In the above code, you see there is a static class XX with a method, NewMethod. If you notice, the NewMethod takes Class1 as a parameter.

What parameter does an extend () method requires?

Parameters of extend() function in Python The list extend() method has only one parameter, and that is an iterable. The iterable can be a list, tuple (it is like an immutable list), string, set or, even a dictionary.

What is the correct definition of extension method?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

Do extension methods have access to private members?

Extension methods can also access private static members of their static utility class. Even though this is tagged as C#, this applies to any of the . NET languages which provide support for extension methods.


1 Answers

When you want to use your extension, add this using statement:

using StringExtensions;

Because of the way Extension methods are declared, visual studio won't find them by itself, and the regular Contains method takes one argument, hence your exception.

like image 146
Louis Kottmann Avatar answered Sep 23 '22 05:09

Louis Kottmann