How could I implement my own deferred execution mechanism in C#?
So for instance I have:
string x = DoFoo();
Is it possible to perform some magic so that DoFoo does not execute until I “use” x?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use lambdas/delegates:
Later you can invoke
doitjust like a method:I think the closest you can get is something like this:
With a definition of
Lazy<T>similar to this (untested):Unfortunately, it seems that the compiler’s type inferencing algorithms can’t auto-infer the type of the
Func<T>and so can’t match it to the implicit conversion operator. We need to explicitly declare the delegate’s type, which makes the assignment statements more verbose: