Just for the hell of it. Not tested extensively.
Code:
class Stopwatch
{
private DateTime m_StartTime; // The time the stopwatch was last started.
private TimeSpan m_Elapsed; // The amount of elapsed time.
private bool m_Running; // Whether the stopwatch is currently running.
/// <summary>
/// The amount of elapsed time.
/// </summary>
public TimeSpan Elapsed
{
get
{
TimeSpan elapsed = this.m_Elapsed;
if (this.m_Running)
{
elapsed = elapsed.Add(DateTime.Now.Subtract(this.m_StartTime));
}
return elapsed;
}
set { this.m_Elapsed = value; }
}
/// <summary>
/// The current state of the stopwatch.
/// </summary>
public bool Running
{
get { return m_Running; }
set { m_Running = value; }
}
public Stopwatch()
{
// Initialise with no time elapsed.
this.m_Elapsed = TimeSpan.Zero;
this.m_Running = false;
}
/// <summary>
/// Start the stopwatch running.
/// </summary>
/// <returns>
/// True if the stopwatch was started; false if the stopwatch was already running.
/// </returns>
public bool Start()
{
bool result;
if (this.m_Running)
{
// The stopwatch is already running.
result = false;
}
else
{
this.m_StartTime = DateTime.Now;
this.m_Running = true;
result = true;
}
return result;
}
/// <summary>
/// Stop the stopwatch running
/// </summary>
/// <returns>
/// True if the stopwatch was stopped; false if the stopwatch was not running.
/// </returns>
public bool Stop()
{
bool result;
if (this.m_Running)
{
this.m_Elapsed = this.m_Elapsed.Add(DateTime.Now.Subtract(this.m_StartTime));
this.m_Running = false;
result = true;
}
else
{
// The stopwatch is not running.
result = false;
}
return result;
}
/// <summary>
/// Resets the elapsed time to zero.
/// </summary>
public void Clear()
{
// Set the start time to now in case the stopwatch is running.
this.m_StartTime = DateTime.Now;
this.m_Elapsed = TimeSpan.Zero;
}
}