Why pass func<T> to constructor rather than T?

Viewed 2196

I came across the accepted answer of this question about dealing with DateTime.Now in unit tests which contains the following code example:

private readonly Func<DateTime> _nowProvider;
public SomeClass(Func<DateTime> nowProvider)
{
    _nowProvider = nowProvider;
}

public bool Foo()
{
    return (_nowProvider().DayOfWeek == DayOfWeek.Sunday);
}

Instantiated as such:

var s = new SomeClass(() => DateTime.Now);

I've not much used Func<T> in C# so I thought I'd take a look at the Microsoft documentation for it which has the following remarks:

You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have no parameters and must return a value.

Why would it be more beneficial in the example to pass a Func<DateTime>, instantiated as Class(() => DateTime.Now) to the constructor

Rather than to just simply pass in a DateTime parameter instantiated as Class(DateTime.Now) to the constructor?

According to the Microsoft documentation mentioned above LINQ lambda constructors also take Func<T> arguments and my experience with these proves they are extremely flexible but I can't understand why?

3 Answers
Related