I like the one for the "as" Cast:
2. The As Cast
How many times have you seen code like this:
1: if (employee is SalariedEmployee)
2: {
3: var salEmp = (SalariedEmployee)employee;
4:
5: pay = salEmp.WeeklySalary;
6:
7: // ...
8: }
This is redundant because you are checking the type twice. Once in the is check and once in the cast. Whenever you find yourself going down this path, prefer the as cast. This handy cast will cast the type if the types are compatible, or return null if not:
1: var salEmployee = employee as SalariedEmployee;
2:
3: if (salEmployee != null)
4: {
5: pay = salEmployee.WeeklySalary;
6:
7: // ...
8: }
The code reads better without the ugly cast, and you avoid double-checking the type.
I also like the Stopwatch Class:
4. The Stopwatch Class
How many times have you wished to log how long a particular piece of code took to execute? Maybe you are trying to track average request time or some such metric, or maybe send a warning message when a stored procedure takes longer than 1 second to execute.
Well, you could do it with DateTime like so:
1: DateTime start = DateTime.Now;
2: SomeCodeToTime();
3: DateTime end = DateTime.Now;
4: Console.WriteLine("Method took {0} ms", (end - start).TotalMilliseconds);
But DateTime is imprecise for this sort of metric. You could also query the high resolution timer using Win32 API calls via PInvoke, but this is also very messy and more error prone.
So what’s a C# developer to do? Enter the Stopwatch class which is in the System.Diagnostics namespace. The Stopwatch class makes it clean and easy to use the high resolution timer through the convenience of a C# class:
1: var timer = Stopwatch.StartNew();
2: SomeCodeToTime();
3: timer.Stop();
4: Console.WriteLine("Method took {0} ms", timer.ElapsedMilliseconds);
Much more precise and very clean. Note there is a static factory method to create a Stopwatch and immediately start it. You also have the option of creating using new and then starting manually as you choose.
2c1ff719-0f2b-4dff-aa3a-44bb6f9f146d|0|.0