c# - Why pass func<T> to constructor rather than T? -
i came across accepted answer of question about dealing datetime.now in unit tests contains following code example:
private readonly func<datetime> _nowprovider; public someclass(func<datetime> nowprovider) { _nowprovider = nowprovider; } public bool foo() { return (_nowprovider().dayofweek == dayofweek.sunday); }
instantiated such:
var s = new someclass(() => datetime.now);
i've not used func<t>
in c# thought i'd take at microsoft documentation it has following remarks:
you can use delegate represent method can passed parameter without explicitly declaring custom delegate. encapsulated method must correspond method signature defined delegate. means encapsulated method must have no parameters , must return value.
why more beneficial in example pass func<datetime>
, instantiated class(() => datetime.now)
constructor
rather pass in datetime
parameter instantiated class(datetime.now)
constructor?
according microsoft documentation mentioned above linq lambda constructors take func<t>
arguments , experience these proves extremely flexible can't understand why?
rather pass in datetime parameter instantiated class(datetime.now) constructor?
because value should current datetime , not 1 when class has been instanciated.
when code runs, func returns date of when code executed.
if datetime stored in field, time of creation, not now.
i have example.
let's create instance of class
@ 23:59:55 on saturday.
10 seconds later, following snipped:
(passeddatetime.dayofweek == dayofweek.sunday);
would return false.
with provider, datetime on sunday - time executed at.
technical:
datetime struct.
when passing datetime method or constructor parameter, passed value, not reference.
thus datetime
not date, snapshot of value.
you can confirm yourself:
var datetime = datetime.now; system.threading.sleep(1000); bool equals = datetime == datetime.now; // false
Comments
Post a Comment