senzacionale
senzacionale

Reputation: 20916

Can i override Convert.ToDateTime()?

can i override Convert.ToDateTime()? I don't want 100 times or more check if string is nul and if is not then convert it to DateTime. Can i override this function to check if is null then will return null otherway convert it.

Upvotes: 3

Views: 1196

Answers (3)

ionden
ionden

Reputation: 12776

ToDateTime can't be overriden but you can use TryParse:

bool valid = DateTime.TryParse("date string", out d);

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500785

No, you can't override static methods. But you can write your own static method:

// TODO: Think of a better class name - this one sucks :)
public static class MoreConvert
{
    public static DateTime? ToDateTimeOrNull(string text)
    {
        return text == null ? (DateTime?) null : Convert.ToDateTime(text);
    }
}

Note that the return type has to be DateTime? because DateTime itself is a non-nullable value type.

You might also want to consider using DateTime.ParseExact instead of Convert.ToDateTime - I've never been terribly fond of its lenient, current-culture-specific behaviour. It depends where the data is coming from though. Do you know the format? Is it going to be in the user's culture, or the invariant culture? (Basically, is it user-entered text, or some machine-generated format?)

Upvotes: 4

Chuck Norris
Chuck Norris

Reputation: 15190

You can use DateTime.Parse instead, if you are sure that your string is in correct format.

Upvotes: 1

Related Questions