Can I override Convert.ToDateTime ()?

Can I override Convert.ToDateTime()? I do not want to check 100 times or more whether the string is zero, and if not, convert it to DateTime. Can I override this function to check if it is null and then return null, otherwise it will convert it.

+3
source share
3 answers

No, you cannot 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 must be DateTime?, because it is DateTimeitself a value type that is not null.

DateTime.ParseExact Convert.ToDateTime - , - . , . ? ? ( , - ?)

+3

ToDateTime , TryParse:

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

Instead, you can use DateTime.Parseit if you are sure that your string is in the correct format.

+1
source

All Articles