Auto Ad Code

Tuesday, August 3, 2010

IsDate() for C# (C Sharp)

As we all know that IsDate() is a function of VB .Net which checks that either a provided object is date or not. Naturally we all think that the same function will be there in C# (C Sharp) as well but this is not the case.
Following is a simple IsDate() function for C# (C Sharp) which acts exactly like VB .Net
=====================================


public static bool IsDate(object pDate)
{
DateTime mDate;
if ((pDate != null) && (pDate.ToString().Trim() != ""))
{
return DateTime.TryParse(pDate.ToString(), out mDate);
}
else
{
return false;
}
}

2 comments:

  1. Just a suggestion,
    you can use Convert.ToString instead of checking if the string is null and using ToString
    public static bool IsDate(object pDate)
    {
    DateTime mDate;
    return DateTime.TryParse(Convert.ToString(pDate), out mDate);
    }
    Thanks,
    Santhosh

    ReplyDelete
  2. You have post this forum blog but i want to know that SecurePage in generic list is undefinded. what is this ??in below code.we have to craete a vo or what ??

    using Microsoft.VisualBasic;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Diagnostics;
    public class SecurePath
    {

    public static bool IsSecure(string path)
    {
    System.Collections.Generic.List lstPages = new System.Collections.Generic.List();

    bool mIsSecure = false;

    try {
    //Fill the list of pages defined in web.config
    System.Collections.Specialized.NameValueCollection sectionPages = (System.Collections.Specialized.NameValueCollection)ConfigurationManager.GetSection("SecurePages");

    foreach (string key in sectionPages) {
    if ((!string.IsNullOrEmpty(key)) && (!string.IsNullOrEmpty(sectionPages.Get(key)))) {
    SecurePage secPage = new SecurePage();
    secPage.PathType = sectionPages.Get(key);
    secPage.Path = key;
    lstPages.Add(secPage);
    }
    }

    //loop through the list to match the path with the value in the list item
    foreach (SecurePage page in lstPages) {
    switch (page.PathType.ToLower().Trim()) {
    case "directory":
    if (path.Contains(page.Path)) {
    mIsSecure = true;
    }
    break;
    case "page":
    if (path.ToLower().Trim() == page.Path.ToLower().Trim()) {
    mIsSecure = true;
    }
    break;
    default:
    mIsSecure = false;
    break;
    }
    }
    } catch (Exception ex) {
    throw new Exception(ex.Message);
    }

    return mIsSecure;
    }
    }

    ReplyDelete