Several methods in our code base use a ‘MaybeObject’ that can be passed into functions when a result might be known, or might rely on an external webservice call that has not yet been carried out. For example, the property below can either have a specified known value, or if not specified and called after the async call is complete it will return the result of the Async call.
private string _internalString;
public string stringProp
{
get
{
if (!string.IsNullOrEmpty(_internalString))
return _internalString;
return resultOfAsyncCallFromSomewhereElse;
}
set { _internalString = value; }
}
Obviously, trying to reference the property before the async call is complete would cause a null reference exception so we also have a flag to check if the value is available.
The question is, in the code below would the creation of the lambda try and evaluate stringProp (which might not be populated yet), or would evaluation be deferred until the resulting Action is called (which would be after checking the async operation is complete)?
public Action ExampleMethod(MaybeObject maybe)
{
return () => doSomethingWithString(maybe.stringProp);
}
Evaluation will be deferred until the resulting Action is called.
The code referenced by a delegate is only executed when the delegate itself is explicitly invoked, regardless of how the delegate itself was created.
For example, these ways of passing the code to execute through the Action delegate are all equivalent, and the
doSomethingWithStringmethod won’t be executed until a call toAction()is made:Explicit method (.NET 1.1):
Anonymous method (.NET 2.0):
Lambda (.NET 3.5):
See also: