I'm writing some code to help facilitate C# method patterns in expression trees. In the case of the using block, there are three ways to use it::
using(var something=IDisposible_value) //1
using(something = IDisposible_value) //2
using(something) //3
Right now my code looks like this:
public static Expression GenerateUsingBoilerPlate(ParameterExpression disposible,Expression toAssign,Expression body)
{
ArgumentValidator.AssertIsNotNull(() => disposible);
ArgumentValidator.AssertIsNotNull(() => body);
var toDispose = Expression.Variable(typeof(IDisposable));
Expression retVal = Expression.TryFinally(
body,
Expression.Block(
new[] { toDispose },
Expression.Assign(
toDispose,
Expression.TypeAs(
disposible,
typeof(IDisposable)
)
),
Expression.IfThen(
Expression.NotEqual(
toDispose,
Expression.Default(
typeof(IDisposable)
)
),
Expression.Call(
toDispose,
"Dispose",
Type.EmptyTypes
)
)
)
);
if (toAssign != null)
{
retVal = Expression.Block(
new[] { disposible },
Expression.Assign(
disposible ,
toAssign
),
retVal
);
}
return retVal;
}
The problem is this code can only handle case 1 and case 3, because I have no way of knowing if the disposible
variable is already bound somewhere else in your expression tree. Can anyone suggest a way to find out if the ParameterExpression
is bound?