Let’s say I am creating an instance of a class object that has both a name and date. Which is considered best practice when setting the date?
var employees = new List<Employee>()
{
new Employee {Name = "Foo", HireDate = new DateTime(2000, 1, 15)},
new Employee {Name = "Bar", HireDate = new DateTime(2001, 5, 25)},
};
or
var employees = new List<Employee>()
{
new Employee {Name = "Foo", HireDate = DateTime.Parse("2000, 1, 15")},
new Employee {Name = "Bar", HireDate = DateTime.Parse("2001, 5, 25")},
};
I am assuming there really isn’t a huge difference, but I am slightly new to C# so I am not sure which is prefered by the majority of C# programmers and why (performance, readability, etc.). Thanks in advance for any insight you can give!
Prefer
new DateTime.In favor of
new, it will allow you to use variables directly:In argument against
Parse, it doesn’t detect errors until runtime:DateTime.Parsewill always have poorer performance, because it needs to run code that detect errors and converts the string to numeric values. It does this while your program is running.However – in cases where you must accept string input (e.g. from a text file), you should use the tool built for the job:
DateTime.Parse.If you’re interested in simplifying the specification of date/time constants in your code, there is a library that Jon Skeet wrote for that.
It is a bit old and unmaintained, but the specific code (extension methods on integer constants/date and time structures) probably doesn’t really need a lot of maintenance.
The source code for those extensions is under
MiscUtil\MiscUtil\Extensions\TimeRelated\(inside the source zip)It will let you write your date times in a friendlier fashion, yet still give you clean code with similar performance to
new DateTime(2012, 11, 13):