.Net 4's new IsNullOrWhiteSpace method

.Net 4 (still in beta right now) has a handy new method that can analye a string and return where it is null or just whitespace versus other text. Here's a quick sample:

ScratchPage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ScratchPage.aspx.cs" Inherits="ScratchPage" %>
 
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="textBox" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

ScratchPage.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class ScratchPage : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(textBox.Text))
        {
            Label1.Text = "The text box is null or has only white space.";
        }
        else
        {
            Label1.Text = "There is a non-null, non-white-space value in the text box";
        }
 
    }
}

 

blog comments powered by Disqus
Tagged as: