If you are anything like me, i.e. has a terrible memory, you might want to keep a recepie of a common task written down somewhere. I find that I frequently forget how to do simple things like declaring custom events properly. And when I need a refresher course I grab a book or surf the Internet only to discover extremly verbose examples and explanations to simple solutions. In order to speed up recovery of forgotten knowledge I’ve decided to make my blog a How-To repository. Here I record solutions and programming practices that I wish to be able to recall quickly. The intent is to adress the basics and keep it brief. Although I will include some explanations and thereby taking a risk of being that which I rally against - verbose.

Since this is supposed to be a post in the How-To section I must include some code. For some reason the basic value types in C# lack methods to check if an object can be interpreted as such a value. I.e. can a string be interpreted as a date? Here I’ll present a simple representation of an IsDate() function that returns true if the submitted object’s value can be interpreted as a date. This code can be adapted to int, decimal and other types quite easily.

public bool IsDate(object o)
{
    try
    {
        DateTime date = DateTime.Parse(o.ToString());
        return true;
    }
    catch
    {
        return false;
    }
}

Technorati Tags: ,

4 Responses to “My personal How-To repository”

Gravatar
Sweden

Ah, smart! To have a repository of that kind in the blog! And good for sharing the little tidbits of technical HowTo’s with others :)

Gravatar
Sweden

Yepp and it beats the “lösbladssystem” with flimsy paper notes lying about and getting lost. :-)

Gravatar
Sweden

Ah, sweet. I love technical blogs :)
Fun to see a bit of C# as well. Not used it myself.

Quick question… Isn’t it a bit dangerous to just use “catch”? Isn’t there a remote possibility that you will catch an error that is not related to the date conversion?
I assume that C# has the ability to catch different kinds of exceptions :)

Gravatar
Sweden

Absatively! I could check for ArgumentNullException or FormatException but since any Exception indicates that the supplied object can not be interpreted as a DateTime value why bother with specifics. Unless the object’s class contains a faulty ToString() implementation in which case something is terribly wrong.

C# isn’t that different from Java att first glance. Reading Martin Fowlers “Refactoring: Improving the Design of Existing Code” it took me several examples before I stumbled on a construct/keyword that told me that it wasn’t C#. :-)

Something to say?