Skip to content

Instantly share code, notes, and snippets.

@MoienTajik
Last active March 18, 2021 09:18
Show Gist options
  • Save MoienTajik/e8b3865542ccbeee2c07b987fdab9a85 to your computer and use it in GitHub Desktop.
Save MoienTajik/e8b3865542ccbeee2c07b987fdab9a85 to your computer and use it in GitHub Desktop.
IClock abstracts DateTime & DateTimeOffset so you can easily mock time and unit-test.
public interface IClock
{
DateTimeOffset UtcNow { get; }
}
public static class Clock
{
private static IClock _instance = new SystemClock();
public static IClock Instance
{
get => _instance;
set => _instance = value ?? throw new ArgumentException("Clock can not be set to null!");
}
public static DateTimeOffset UtcNow => _instance.UtcNow;
}
internal class SystemClock : IClock
{
public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
}
// Usage
public class Program
{
public static void Main()
{
var now = Clock.UtcNow();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment