Thursday, April 14, 2011

Extension method

This is a new feature that has been added to C# in C# 3.0. One of the usefulness of extension method is to shorten the codes that we used to write.

For example, we want to convert a string value to integer. Normally, we will write code like this:

int i = 0;
            if (Int32.TryParse(s, out i))
            {
                return i;
            }
            else
            {
                return 0;
            }

Instead of doing this, we may already have declared a static function which will do the conversion like this:

public class MyClass
    {
        public static int StrToInt(string s)
        {
            int i = 0;
            if (Int32.TryParse(s, out i))
            {
                return i;
            }
            else
            {
                return 0;
            }
        }
    }

So, we will write our code like this:

int i = MyClass.StrToInt("1234");

Now, with extension method, the data type conversion call will be shorten:

    public static class MyClass
    {
        public static int StrToInt(this string s)
        {
            int i = 0;
            if (Int32.TryParse(s, out i))
            {
                return i;
            }
            else
            {
                return 0;
            }
        }
    }

    public class Test11
    {
        public void MyTestMethod()
        {
           // We don't have to write like this anymore:
           //int i = MyClass.StrToInt("1234");

           // Now, we can do this:
            int i = "1234".StrToInt();
        }
    }

No comments:

Post a Comment