Best practice: new DateTime () vs DateTime.Parse () function

Let's say I create an instance of a class object that has a name and a date. What is considered best practice for 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 suppose there really isn't a big difference, but I'm a little new to C #, so I'm not sure what most C # programmers prefer and why (performance, readability, etc.). Thanks in advance for any insight you can give!

+6
source share
3 answers

Prefers new DateTime .

In favor of new , this will allow you to use variables directly:

 // clean because the variable is applied directly to the function int year = 2000; var date1 = new DateTime(year, 1, 15); var date1 = new DateTime(year, 7, 3); var date1 = new DateTime(year, 8, 19); // kind of gross and prone to errors because it is appended to the string int day = 23; var date1 = DateTime.Parse("2001, 5, " + day.ToString()); 

In the argument against Parse it does not detect errors until runtime:

 var date1 = new DateTime(200fdsa, 1, 15); // Error on compile var date2 = DateTime.Parse("2001fdsjf, 5, 25"); // Must run to find the error 

DateTime.Parse will always have lower performance because it needs to run code that detects errors and converts the string to numeric values. He does this while your program is running.

However, in cases where you must accept string input (for example, from a text file), you must use the tool created for the job: DateTime.Parse .


If you are interested in simplifying the specification of date / time constants in your code, there is a library that John Skeet wrote for this.

It is a bit old and not supported, but the specific code (extension methods for integer constants / date and time structures) probably does not need a lot of maintenance.

The source code for these extensions is under MiscUtil\MiscUtil\Extensions\TimeRelated\ (inside the source zip)

This will allow you to write your dates in a more friendly manner, but you will get clean code with similar performance until new DateTime(2012, 11, 13) :

 DateTime someDateAndTime = 19.June(1976) + 8.Hours(); 
+12
source

I believe that this is ultimately subjective, but I cannot imagine any reason to use Parse in this situation. Why perform (inefficient) parsing on a simple constructor that takes the actual values โ€‹โ€‹of the components?

+6
source

I would use new DateTime() in the above example. You know exactly what the year / month / day data is. Why create a string and parse it?

+4
source

Source: https://habr.com/ru/post/901363/


All Articles