[C#] I wish I knew : Stopwatch.StartNew()

I've been a professional C# developer for years now, but I'm still discovering trivial stuffs. In "I wish I knew", I describe a feature that I missed.

When you need to measure the performance of a C# program, you have basically two solutions: either use a profiler or add instrumentation in the source code.

The Stopwatch is the class to use when you want to add instrumentation.

Stopwatch picture

Here is how I've been using it for years:

var chrono = new Stopwatch();

chrono.Start();
// perform time-consuming operation
chrono.Stop();

I hate writing this because it bloats the original code. I always wished there existed a shorter solution.

Surprise! There is a static method StartNew() just for that:

var chrono = Stopwatch.StartNew();
// perform time-consuming operation
chrono.Stop();

Image credit: Flick user purplemattfish