Monday 11 February 2013

Change phone number format using extension method in C# and asp.net

Extension Method is a very popular topic in C# that is used to increase the functionality of any Type variable that is mostly used in whole application or in terms of single use also. Best example we can see for Phone Number Format, user can enter 10 digit number in text box and we need to save it in different format for example US Phone Number Format (xxx)-(xxxx)-xxx.

First create a static class with a static method. Here I have posted a code example for Extension Method Of String Type. This example converts a normal Phone number in US format. You can write here your own code for any functionality. The main point is this keyword in Method USPhoneNumberFormat(this string value), it will fetch value from current string object.

Class:
public static class ExtensionMethods
    {
        public static string USPhoneNumberFormat(this string value)
        {
            if (value.Length == 10)
            {
                StringBuilder phoneNumber = new StringBuilder();                    

               for (int i = 0; i < 10; i++)
                {
                    if (i == 0)
                    {                       
                        phoneNumber.Append("(");
                        phoneNumber.Append(value[i]);
                    }
                    else if (i == 3 )
                    {
                        phoneNumber.Append(")-(");
                        phoneNumber.Append(value[i]);
                    }
                    else if (i == 7 )
                    {
                        phoneNumber.Append(")-");
                        phoneNumber.Append(value[i]);
                    }
                    else
                    {
                        phoneNumber.Append(value[i]);
                    }
                }
                return phoneNumber.ToString();
               }
            return value;
        }
    }

aspx.cs page:

 string value = "1234560789";
 value=value.USPhoneNumberFormat();




No comments:

Post a Comment