1

This is simple word count extension method.

public static class StringExtension
    {
        public static int WordCount(this string s)
        {
            int count = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] != ' ')
                {
                    if ((i + 1) == s.Length)
                    {
                        count++;
                    }
                    else
                    {
                        if (s[i + 1] == ' ')
                        {
                            count++;
                        }
                    }
                }
            }
            return count;
        }
    }

Just tell me reason why extension method is static and why it is wrapped in static class ?

Mist
  • 684
  • 9
  • 30
  • 1
    How else would it work? If it wasn't static, what would you instantiate to call it on and how would the syntax for calling an extension method present this? – Tom W Jun 06 '18 at 10:53
  • Sir if possible please show the reason with few points. thanks – Mist Jun 06 '18 at 10:54
  • 1
    The reason is that the language design team chose to do it like this. – Tom W Jun 06 '18 at 10:54
  • just as String,Join is available, you didnt need to make the string class did you? you want your extension or its kinda no longer an extension of the string class is it – BugFinder Jun 06 '18 at 10:55
  • 1
    That is what normal instance methods look like as well, under the hood. They also have a *this* argument, you just don't have to explicitly declare it. The design team made the most logical and consistent choice for the required syntax. – Hans Passant Jun 06 '18 at 10:55

0 Answers0