C# 3.0 Enhancements: Extension Methods

C# 3.0 Enhancements: Extension Methods

  • Comments 4

Extension Methods are different way of implementing static method. In C# 3.0 it allows us to extend any type and add method for that type. While writing extension method you need to

Ø       declare a public static method

Ø       the first parameter of that method should be the type of the object

Ø       this” keyword has to be the first part of the first argument of that method

 

This helps us to extend methods for the types that are already part of .NET Framework.

 

If you have declared an Extension Method like

 

public static void Foo(this string sVal)

{

    //Do something

}

 

If you make a call to this method the syntax will look like,

 

string s = "Something for test";

s.Foo();

 

The actual call will happen like

myExtensions.Foo(s); Here myExtensions is the static class under which you have defined the Foo method.

 

Another first class treatment of static method in .NET. It allows us to feel the magic as if we are writing CLR code. You can define most of your utility functions in form of extension method and by using the “using” block you can use them in your code behind file.

 

 

The real life example of the extension method may look like,

 

public static class myExtensions

{

    public static string GetString(this string[] arrStr)

    {

        StringBuilder sb = new StringBuilder();

 

        foreach (string s in arrStr)

        {

            if (sb.Length != 0)

                sb.Append(",");

               

                sb.Append(s);               

        }

        return sb.ToString();

    }      

}

 

 

class Program

{        

    static void Main(string[] args)

    {

        string[] sTest = new string[]

{ "Wriju", "Writam", "Deb", "Sumitra" };

 

        Console.WriteLine(sTest.GetString());

        Console.ReadKey();

    }                       

}

 

 

Namoskar!!!

Leave a Comment
  • Please add 6 and 6 and type the answer here:
  • Post
  • This is just like objective-c.  At least give em some credit.

  • won't string.Join(",", arrStr) work instead of the loop?

      foreach (string s in arrStr)

           {

               if (sb.Length != 0)

                   sb.Append(",");

                   sb.Append(s);              

           }

  • It would work, but here you need to know the great advantage of using StringBuilder.

    String is immutable. meaning, every time you use a string - you allocate space for the new object.

    Therefore, In case you have methods which alter  strings, you might want to choose the StringBuilder object.

    Please consider reading the following article:

    http://msdn2.microsoft.com/en-us/library/2839d5h5.aspx

    A good discussion about it is available here:

    http://blogs.msdn.com/msdnstudentflash/archive/2005/01/31/364217.aspx

  • What are the C# programming enhancements in 3.0,3.5

Page 1 of 1 (4 items)