"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Friday, January 18, 2013

Extension Method in c#

Extension Method in c#

first of all created a new static class DateTimeExtensionMethod



public static class DateTimeExtensionMethod
{
    public static string DateFormat2d(this DateTime dt)
    {
        return dt.ToString("d");  //output format looks [1/8/2013]
    }

    public static string Date2String(this DateTime dt)
    {
        try
        {
            return dt.ToString(); // output format looks [1/8/2013 2:16:18 PM]
        }
        catch (Exception)
        {
            return "";
        }
    }

    public static string DateFormat2U(this DateTime dt)
    {
        try
        {
            return dt.ToString("U"); // output format looks [Tuesday, January 08, 2013 8:46:18 AM]
        }
        catch (Exception)
        {
            return "";
            //here i'm elabrating with the help of an example of converting datetime to string by custom format
        }
    }

    public static string GetFirstThreeCharacters(this string txt)
    {
        try
        {
            if (txt.Length < 3)
            {
                return txt;
            }
            else
            {
                return txt.Substring(0, 3);
            }
        }
        catch (Exception)
        {
            return "";
        }
    }

    public static bool CheckAValue(this string txt)
    {
        try
        {
            if (txt.Contains("a"))
                return true;
            else
                return false;
        }
        catch (Exception)
        {
            return false;
        }
    }
}



Later build the solution  and on page



    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("<span style='color:red'> Datetime ToString() converter to " + DateTime.Now.Date2String() + "</span></br>");
        // Response.Write("<span style='color:green'> Datetime ToString('d') converter to " + DateTimeExtensionMethod.DateFormat2d(DateTime.Now) + "</span></br>");
        Response.Write("<span style='color:blue'> Datetime ToString('U') converter to " + DateTime.Now.DateFormat2U() + "</span></br>");
        Response.Write("<span style='color:green'> Datetime ToString('d') converter to " + DateTime.Now.DateFormat2d() + "</span></br>");
        string txt = "Myself Arun Aravind";
        Response.Write("<span style='color:brown'>" + txt + " [returns first 3 letters]" + txt.GetFirstThreeCharacters() + "</span></br>");
        Response.Write(txt.CheckAValue() ? txt + " :: string contains letter 'a'" : txt + " :: string doent have letter 'a'");
    }


Output

 

If u had any trouble just ask, Happy to help u :)
Stay Tune...
 Have a nice day... 'N happy Coding :)

No comments: