Mike
Mike

Reputation: 3284

Is there a better way of checking the type in a datarow?

I have to check whether the first cell in my datarow is a datetime object.I'm doing the following for it.Could you please let me know whether there is a better way to do it?

public bool ShouldProcess(DataRow theRow)
        {
            try
            {                
                Convert.ToDateTime(theRow[0]);
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

Thanks, -M

Upvotes: 2

Views: 69

Answers (4)

Jonathan Wood
Jonathan Wood

Reputation: 67295

Have you tried if (theRow[0] is DateTime)?

Upvotes: 1

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19347

You can use

if(theRow[0] is DateTime)
    return true;
else
    return false

The is keyword checks the type of the left-hand side to see whether it is compatible with the type given on the right-hand side.

Upvotes: 1

Adriaan Stander
Adriaan Stander

Reputation: 166486

Rather have a look at using

DateTime.TryParse Method or even DateTime.TryParseExact Method

Remember that these Methods return a bool value, so you can use it to return the bool value.

something like

DateTime dateVal;
return DateTime.TryParse(theRow[0], out dateVal);

Upvotes: 0

Adeel
Adeel

Reputation: 19238

No need to place try/catch

DateTime outDate =  null;
DateTime.TryParse(theRow[0], out outDate);
if(outDate != DateTime.MinDate)
{
//Successfully converted
}

Upvotes: 1

Related Questions