C# 3.0 Features - Part 3.6 Extension Methods

Apr
24
2011
In Categories: .NET | CLR
Tags | |

You can see part 0 here, part 1 here, part 2 here, part 3 here, part 4 here and part 5 here

This feature adds extension to your design. if we have closed assembly and we need to add function to this class. We can use extension methods as we see in the next piece of code

    1 namespace ExtensionMethods

    2 {

    3     public static class MyExtensions

    4     {

    5         public static int WordCount(this string str)

    6         {

    7            var exEmptyLines = StringSplitOptions.RemoveEmptyEntries;

    8            var strArray = str.Split(new char[] { ' ', '.', '?' }, exEmptyLines);

    9            return strArray.Length;

   10         }

   11     }

   12 }

And we can use the word count function normally as it is used in string class. The only thing we have to do is to add the namespace

    1 using ExtensionMethods;

    2 

    3 class Test

    4 {

    5     static void Main()

    6     {

    7         string s = “Hello Extension Methods”;

    8         System.Console.WriteLine(s.WordCount());

    9     }

   10 }

The only thing that we add to the function is this line of code as in this function signature

    5 public static int WordCount(this String str)

Comments are closed