C# tip: How do I specify a default value for a DateTime method parameter?

Posted: (EET/GMT+2)

 

Today's post is a quick C# programming tip when working with DateTime types. Assume you have a method like this:

public static int CalculateSomething(string calculationMethod, DateTime startDate)

This is all fine, but now, you want to make the startDate parameter optional. Your first attempt might be:

public static int CalculateSomething(string calculationMethod,
  DateTime startDate = DateTime.MinValue)

However, this fails with the compiler error "CS1736: Default parameter value for 'startDate' must be a compile-time constant", and thus won't work. However, in this situation, you can use C#'s default keyword for a convenient solution to the problem:

public static int CalculateSomething(string calculationMethod,
  DateTime startDate = default(DateTime))

This solution keeps the compiler happy, and effectively, is the same result as the previous example: if the startDate parameter is not given a value, it defaults to DateTime.MinValue, which in turn is 1/1/0001 at 00:00 (midnight).

Happy hacking!