C# Метод розширення

2075 / C# / Класи / Метод розширення (extension methods)

 

class Program
{
  static void Main(string[] args)
  {
    string s = "Hello world";
    char c = 'l';
    int i = s.Count(c); // 3, передаємо лише 2-гий параметр
    Console.WriteLine(i);
  }
}

public static class StringExtension
{
  public static int Count(this string str, char c)
  {
    int counter = 0;
    for (int i = 0; i < str.Length; i++)
    {
      if (str[i] == c)
        counter++;
    }
    return counter;
  }
}