0

If this question is too simple I apologize in advance.

Why does the method NthIndexOf found in the link below require a static class and also static class member?

C# - indexOf the nth occurrence of a string?

Community
  • 1
  • 1
GoBeavs
  • 499
  • 2
  • 10
  • 25

3 Answers3

5

Because it is an extension method (MSDN) -- notice the keyword this before the first parameter.

This allows you to use the syntax:

var result = "foo bar".NthIndexOf("o", 1);

…as though you had added the NthIndexOf method to the System.String type. This would be available anywhere the namespace for that static class was available (using MyExtensions; for example).

Extension methods must be declared as static methods of public, non-nested static classes, but the same logic can be encapsulated without using an extension method, in which case there would be no requirement to use a static class & method.

Jay
  • 56,361
  • 10
  • 99
  • 123
3

Because it's an EXTENSION METHOD (EM).

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 a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

For example:
String is a .Net type. Prior to EM, without deriving, you cannot add your own method to string type. Even if you did so by deriving, that method would be counted as method of derived type and not of string type.

But now with EM's you can do so without deriving from it.

Requirements of EM (in C#)

  1. They have to be public and static
  2. The class in which they are defined is also public and static.
  3. Most Important: First parameter should be that type for which you are creating your EM and should have this keyword in front of it. Without it, your method would not be an EM and would be a static method only.

In your earlier scenaro your EM NthIndexOf is defined in static class StringExtender

public static class StringExtender
{
    public static int NthIndexOf(this string target, string value, int n)
    {
        ....
    }
}

Now since first parameter contains this in front of string so you can call it as

int result = "My string".NthIndexOf("M", 0);

If it was not EM and a plain static method like this

public static class StringExtender
{
    public static int NthIndexOf(string target, string value, int n)
    {
        ....
    }
}

then it had to be called like

int result = NthIndexOf("My string", "M", 0);
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

It's an extension method which requires the static keyword.

Jim O'Neil
  • 23,344
  • 7
  • 42
  • 67