<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Extension Methods</title>
</head>
<body>
<div id="pageContent">
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Test" OnClick="Button1_Click" />
<hr />
<h2>Next day is</h2>
<asp:Label ID="Label1" runat="server" />
</form>
</div>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
public static class StringExtensions
{
public static bool IsInt32(this string content)
{
int number;
bool result = Int32.TryParse(content, out number);
return result;
}
public static bool IsDate(this string content)
{
DateTime date;
bool result = DateTime.TryParse(content, out date);
return result;
}
public static DateTime ToDate(this string content)
{
DateTime date;
bool result = DateTime.TryParse(content, out date);
if (result)
return date;
else
return DateTime.MinValue;
}
public static int ToInt32(this string content)
{
int number;
bool result = Int32.TryParse(content, out number);
if (result)
return number;
else
return Int32.MinValue;
}
}
public partial class Default : System.Web.UI.Page
{
public void Button1_Click(object sender, EventArgs e)
{
string content = TextBox1.Text;
if (content.IsDate())
{
DateTime date = content.ToDate();
Label1.Text = date.AddDays(1).ToString("dd MMMM yyyy");
}
else
{
Label1.Text = "Not a valid date.";
}
}
}