Casting an expression to another one

c# casting expression generics graphdiff

Question

I have following expression

Expression<Func<T, object>> expr1;

Is there any way to cast it to

Expression<Func<IUpdateConfiguration<T>, object>>?

[Update]

Or create a new Expression<Func<IUpdateConfiguration<T>, object>> from the existing Expression<Func<T, object>>?

1
5
7/6/2014 9:51:50 AM

Popular Answer

No. The first is a function that takes a T and returns an object. The second one accepts a IUpdateConfiguration<T> and returns an object. Unless the T is also a IUpdateConfiguration<T>, you cannot cast this. If you know of a way to convert a IUpdateConfiguration<T> into a T, you can make a new expression, but that's different than casting.

For example, given this:

Expression<Func<IUpdateConfiguration<T>, T> expr2;

You can make your desired function like this:

Expression<Func<IUpdateConfiguration<T>, object>> = 
    (IUpdateConfiguration<T> t) => expr1(expr2(t));

But this will have a completely different expression body than the original one. That may or may not be a problem, depending what you're trying to accomplish.

3
7/6/2014 7:31:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow