Expression.Call, Int32 and Enum - c#

Can't figure out how to build an expression that compares an enum type with an int. I have a MVC site with Kendo components embedded. In the view-class, the property is an ENUM, but the view returns an Int32 (the source is a Kendo IFilterDescriptor).
So the problem is...: I receive an int from the view, build the expression, that fails because an enum is expected. Fix this by converting the int to its enum representation, but then it fails when querying the database, because the database expect an Int32.
public static Expression<Func<DOMAIN, bool>> GetExpressionsFromFilterDescription<DOMAIN, VIEW>(this IEnumerable<IFilterDescriptor> _this)
{
Expression expressions = null;
ParameterExpression pe = Expression.Parameter(typeof(DOMAIN), "x");
foreach (FilterDescriptor item in _this)
{
MemberExpression member = Expression.Property(pe, item.Member);
ConstantExpression value = Expression.Constant(item.Value);
Expression exp = null;
switch (item.Operator)
{
case FilterOperator.IsEqualTo:
exp = Expression.Equal(member, value);
From what I understand, Expression.Call() should be able to fix this, I just can't figure out how to do this.
Any help would be appreciated.
BR Peter
UPDATE
Converting the value like below, does fix the expression problem (the "The binary operator Equal is not defined for the types..." error), but then I get a new error querying the database: "Type mismatch in NHibernate.Criterion.SimpleExpression: Status expected type System.Int32, actual type...".
exp = Expression.Equal(member, Expression.Convert(value, typeof(MyEnum)));
The fix, as I see it, is either by building my own compare (Expression.Call ?) or by telling that the type (in item.Member) is an int and not an enum, but I don't know how or if this is the right way.
Thanks.
UPDATE UPDATE
It seems like that the second part of the problem is due to NHibernate.QueryOver and its limitations. Once changed to NHibernate.Linq, the query part of the problem, went away.
As for the Expression part I have fixed the problem by adding an attribute to the property telling how the value should be converted. I am not using Expression.Convert (but I could have), the conversion happens in the received filter description before building the expression.
Thanks for your time and help. I will accept the answers related to Expression.Convert since it could fix the problem. I still do want to understand the Expression.Call() method - so please feel free to comment on that. Thanks.

Wouldn't this do the trick?
MemberExpression member = Expression.Convert(
Expression.Property(pe, item.Member), typeof(int);
ConstantExpression value = Expression.Constant((int)item.Value);

You can use Expression.Convert to convert an expression of an enumtype to anint` (assuming that the underlying type of the enum is an int).

I don't exactly see your enum you are comparing to, is it item.Value?
You can always cast the value of an enum to a number to compare it to a number or feed it into systems that don't recognize enums:
enum Blah
{
Tom,
Rick,
Harry
}
if ((Int32)Blah.Tom == 0)
{
}

Related

C# Cannot use Linq DefaultIfEmpty in ushort list items?

I want to take max value of ushort list and when that list is empty I want set "1" for default value.
For example:
List<ushort> takeMaxmumId = new List<ushort>();
var max = takeMaxmumId.Select(x=>x).DefaultIfEmpty(1).Max();
In my Example Visual Studio Show me this error:
'IEnumerable' does not contain a definition for
'DefaultIfEmpty' and the best extension method overload
'Queryable.DefaultIfEmpty(IQueryable, int)' requires a
receiver of type 'IQueryable'
When my list type were int I have not any problem, What is this problem in ushort type? And how can I fix this with best way?
The problem is that Select produces an IEnumerable<ushort>, while DefaultIfEmpty supplies an int default. Hence, the types do not match.
You can fix this by forcing ushort type on the default:
var max = takeMaxmumId.Select(x=>x).DefaultIfEmpty<ushort>(1).Max();
// ^^^^^^^^^^^^^
// This part can be removed
Demo.
You can also convert sequence elements to int:
var max = takeMaxmumId.Select(x => (int)x).DefaultIfEmpty(1).Max();
Since your data type is ushort you will have to staisfy the alternative orverload of DefaultIfEmpty extension method. i.e DefaultIfEmpty(this IEnumerable source, TSource defaultValue);
So you will have to cast to your source to type ushort.
var max = takeMaxmumId.Select(x => x).DefaultIfEmpty( (ushort) 1).Max();
You could try this one:
var max = takeMaximumId.DefaultIfEmpty((ushort)1).Select(x => x).Max();
The problem is due to the fact that passing 1 without the cast to ushort you can't apply the extension method DefaultIfEmpty, because 1 is interpreted as int and the list you want to apply this is of type List<ushort>. If you write the following
var max = takeMaximumId.DefaultIfEmpty(1).Select(x => x).Max();
you would get the error message below, which explains the above
statement:
'List' does not contain a definition for 'DefaultIfEmpty' and
the best extension method overload
'Queryable.DefaultIfEmpty(IQueryable, int)' requires a
receiver of type 'IQueryable'
As a side note, despite the fact that dasblinkenlight has already mentioned this in his post, you don't need at all the Select, since you don't make any projection there. You just want to get the maximum value of the numbers contained in your list.

Switch without cases (but with default) in System.Linq.Expressions

I have tried to create a switch expression with System.Linq.Expressions:
var value = Expression.Parameter(typeof(int));
var defaultBody = Expression.Constant(0);
var cases1 = new[] { Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), };
var cases2 = new SwitchCase[0];
var switch1 = Expression.Switch(value, defaultBody, cases1);
var switch2 = Expression.Switch(value, defaultBody, cases2);
but in the last line I get an ArgumentException:
Non-empty collection required. Parameter name: cases
What is the reason of this exception? May be this a bug in Expression.Switch(…)?
In a C# a switch with "default" part only is correct:
switch(expr) {
default:
return 0;
}//switch
UPD: I have submitted an issue to the CoreFX repo on GitHub
There isn't a complete analogy between C#'s switch and SwitchExpression. In the other direction, consider that you can have:
var value = Expression.Parameter(typeof(int));
var meth = Expression.Lambda<Func<int, string>>(
Expression.Switch(
value,
Expression.Call(value, typeof(object).GetMethod("ToString")),
Expression.SwitchCase(Expression.Constant("Zero"), Expression.Constant(0, typeof(int))),
Expression.SwitchCase(Expression.Constant("One"), Expression.Constant(1, typeof(int)))),
value
).Compile();
Console.WriteLine(meth(0)); // Zero
Console.WriteLine(meth(1)); // One
Console.WriteLine(meth(2)); // 2
Here the SwitchExpression returns a value which is something switch cannot do.
So, just as being able to do something with SwitchExpression does not mean you can do it with a switch, so too there's no reason to assume that being able to do something with a switch means you can do it with a SwitchExpression.
That said, I see no good reason why SwitchExpression was set this way, except perhaps that it simplifies the case where an expression has no cases and no default body. That said, I think this was likely just a matter of the expression being generally intended to have multiple cases, and that was what it was coded to support.
I've submitted a pull-request to .NET Core that would allow such case-less expressions, by producing a SwitchExpression where the default value for the type of switchValue has the same body as the default body. This approach means anything that would be surprised by a SwitchExpression with no cases should still cope, avoiding backwards-compatibility issues. The case of there being no default either is dealt with by creating a noop expression that does nothing, so the only case that now still throws an ArgumentException is if there is no case and no default and the type is explicitly set to something other than void, this case being invalid under the typing rules that must obviously still be kept.
[Update: That approach was rejected, but a later pull-request was accepted, so case-less SwitchExpressions are now allowed by .NET Core, though if and when that is adopted by other versions of .NET is another matter].
In the meantime, or if you use another version of .NET, you're best-off using a helper method like:
public static Expression SwitchOrDefault(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, IEnumerable<SwitchCase> cases)
{
if (cases != null)
{
// It's possible that cases is a type that can only be enumerated once.
// so we check for the most obvious condition where that isn't true
// and otherwise create a ReadOnlyCollection. ReadOnlyCollection is
// chosen because it's the most efficient within Switch itself.
if (!(cases is ICollection<SwitchCase>))
cases = new ReadOnlyCollection<SwitchCase>(cases);
if (cases.Any())
return Switch(type, switchValue, defaultBody, comparison, cases);
}
return Expression.Block(
switchValue, // include in case of side-effects.
defaultBody != null ? defaultBody : Expression.Empty() // replace null with a noop expression.
);
}
Overloads like:
public static Expression SwitchOrDefault(Expression switchValue, Expression defaultBody, params SwitchCase[] cases)
{
return SwitchOrDefault(switchValue, defaultBody, null, (IEnumerable<SwitchCase>)cases);
}
And so on can then be added.
This results in a trimmer Expression overall than my pull-request, because it cuts out the switch entirely in the no-cases case and just returns the default body. If you really need to have a SwitchExpression then you could create a similar helper method that follows the same logic as that pull-request does in creating a new SwitchCase and then using that.

Dynamic Linq cannot parse long.Parse()

I'm using the Dynamic Linq Library to parse a boolean expression. In this method:
public static LambdaExpression Parse(SearchQuery query)
{
string compilableExpression = BuildCompilableExpression(query);
ParameterExpression parameter = System.Linq.Expressions.Expression.Parameter(typeof(EventListItem));
return System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { parameter }, null, compilableExpression);
}
BuildCompilableExpression returns this string:
"long.Parse(InstanceID.ToString()) == long.Parse(\"2\")"
Which is correct (InstanceID is a property in the EventListItem), however, the call to ParseLambda() failes with this exception:
No property or field 'long' exists in type 'EventListItem'
I've tried parsing an expression that contains string.Compare() and that works just fine, so I don't understand why long.Parse()doesn't work. I was just wondering if anyone has ever done this. Any help is appreciated.
long isn't the name of a type, it is a shortcut provided by C#. Int64 is the technical name, have you tried that? Similarly String is the name of the string type.
Note that string might have worked because while C# is case sensitive, the analyzer may or may not be.
The type long does not exist in .NET. long is a C# keyword and is an alias for the .NET type System.Int64. Try using Int64.Parse(...).

Why can't an anonymous method be assigned to var?

I have the following code:
Func<string, bool> comparer = delegate(string value) {
return value != "0";
};
However, the following does not compile:
var comparer = delegate(string value) {
return value != "0";
};
Why can't the compiler figure out it is a Func<string, bool>? It takes one string parameter, and returns a boolean. Instead, it gives me the error:
Cannot assign anonymous method to an
implicitly-typed local variable.
I have one guess and that is if the var version compiled, it would lack consistency if I had the following:
var comparer = delegate(string arg1, string arg2, string arg3, string arg4, string arg5) {
return false;
};
The above wouldn't make sense since Func<> allows only up to 4 arguments (in .NET 3.5, which is what I am using). Perhaps someone could clarify the problem. Thanks.
UPDATE: This answer was written over ten years ago and should be considered to be of historical interest; in C# 10 the compiler will infer some delegate types.
Others have already pointed out that there are infinitely many possible delegate types that you could have meant; what is so special about Func that it deserves to be the default instead of Predicate or Action or any other possibility? And, for lambdas, why is it obvious that the intention is to choose the delegate form, rather than the expression tree form?
But we could say that Func is special, and that the inferred type of a lambda or anonymous method is Func of something. We'd still have all kinds of problems. What types would you like to be inferred for the following cases?
var x1 = (ref int y)=>123;
There is no Func<T> type that takes a ref anything.
var x2 = y=>123;
We don't know the type of the formal parameter, though we do know the return. (Or do we? Is the return int? long? short? byte?)
var x3 = (int y)=>null;
We don't know the return type, but it can't be void. The return type could be any reference type or any nullable value type.
var x4 = (int y)=>{ throw new Exception(); }
Again, we don't know the return type, and this time it can be void.
var x5 = (int y)=> q += y;
Is that intended to be a void-returning statement lambda or something that returns the value that was assigned to q? Both are legal; which should we choose?
Now, you might say, well, just don't support any of those features. Just support "normal" cases where the types can be worked out. That doesn't help. How does that make my life easier? If the feature works sometimes and fails sometimes then I still have to write the code to detect all of those failure situations and give a meaningful error message for each. We still have to specify all that behaviour, document it, write tests for it, and so on. This is a very expensive feature that saves the user maybe half a dozen keystrokes. We have better ways to add value to the language than spending a lot of time writing test cases for a feature that doesn't work half the time and doesn't provide hardly any benefit in cases where it does work.
The situation where it is actually useful is:
var xAnon = (int y)=>new { Y = y };
because there is no "speakable" type for that thing. But we have this problem all the time, and we just use method type inference to deduce the type:
Func<A, R> WorkItOut<A, R>(Func<A, R> f) { return f; }
...
var xAnon = WorkItOut((int y)=>new { Y = y });
and now method type inference works out what the func type is.
Only Eric Lippert knows for sure, but I think it's because the signature of the delegate type doesn't uniquely determine the type.
Consider your example:
var comparer = delegate(string value) { return value != "0"; };
Here are two possible inferences for what the var should be:
Predicate<string> comparer = delegate(string value) { return value != "0"; }; // okay
Func<string, bool> comparer = delegate(string value) { return value != "0"; }; // also okay
Which one should the compiler infer? There's no good reason to choose one or the other. And although a Predicate<T> is functionally equivalent to a Func<T, bool>, they are still different types at the level of the .NET type system. The compiler therefore cannot unambiguously resolve the delegate type, and must fail the type inference.
Eric Lippert has an old post about it where he says
And in fact the C# 2.0 specification
calls this out. Method group
expressions and anonymous method
expressions are typeless expressions
in C# 2.0, and lambda expressions join
them in C# 3.0. Therefore it is
illegal for them to appear "naked" on
the right hand side of an implicit
declaration.
Different delegates are considered different types. e.g., Action is different than MethodInvoker, and an instance of Action can't be assigned to a variable of type MethodInvoker.
So, given an anonymous delegate (or lambda) like () => {}, is it an Action or a MethodInvoker? The compiler can't tell.
Similarly, if I declare a delegate type taking a string argument and returning a bool, how would the compiler know you really wanted a Func<string, bool> instead of my delegate type? It can't infer the delegate type.
The following points are from the MSDN regarding Implicitly Typed Local Variables:
var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.
It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.
MSDN Reference: Implicitly Typed Local Variables
Considering the following regarding Anonymous Methods:
Anonymous methods enable you to omit the parameter list.
MSDN Reference: Anonymous Methods
I would suspect that since the anonymous method may actually have different method signatures, the compiler is unable to properly infer what the most appropriate type to assign would be.
My post doesn't answer the actual question, but it does answer the underlying question of :
"How do I avoid having to type out some fugly type like Func<string, string, int, CustomInputType, bool, ReturnType>?" [1]
Being the lazy/hacky programmer that I am, I experimented with using Func<dynamic, object> - which takes a single input parameter and returns an object.
For multiple arguments, you can use it like so:
dynamic myParams = new ExpandoObject();
myParams.arg0 = "whatever";
myParams.arg1 = 3;
Func<dynamic, object> y = (dynObj) =>
{
return dynObj.arg0.ToUpper() + (dynObj.arg1 * 45); //screw type casting, amirite?
};
Console.WriteLine(y(myParams));
Tip: You can use Action<dynamic> if you don't need to return an object.
Yeah I know it probably goes against your programming principles, but this makes sense to me and probably some Python coders.
I'm pretty novice at delegates... just wanted to share what I learned.
[1] This assumes that you aren't calling a method that requires a predefined Func as a parameter, in which case, you'll have to type that fugly string :/
Other answers were correct at the time they were written, but starting from C# 10.0 (from 2021), the compiler can infer a suitable delegate type (like some Func<...>, Action<...> or generated delegate type) in such cases.
See C# 10 Features - Lambda improvements.
var comparer = delegate(string value) {
return value != "0";
}; // OK in C# 10.0, picks 'Func<string, bool>' in this case
Of course the more usual syntax is to us =>, so:
var comparer = (string value) => {
return value != "0";
}; // OK in C# 10.0, picks 'Func<string, bool>' in this case
How is about that?
var item = new
{
toolisn = 100,
LangId = "ENG",
toolPath = (Func<int, string, string>) delegate(int toolisn, string LangId)
{
var path = "/Content/Tool_" + toolisn + "_" + LangId + "/story.html";
return File.Exists(Server.MapPath(path)) ? "<a style=\"vertical-align:super\" href=\"" + path + "\" target=\"_blank\">execute example</a> " : "";
}
};
string result = item.toolPath(item.toolisn, item.LangId);

Can I capture a local variable into a LINQ Expression as a constant rather than a closure reference?

I'd like to say
int x = magic(), y = moremagic();
return i => i + (x/y);
and have the x be captured as a constant instead of a variable reference. The idea is that x will never change and so when the expression is later compiled, the compiler to can do constant folding and produce more efficient code -- i.e. calculating x/y once instead of on every call, via pointer dereferences into a closure record.
There is no way to mark x as readonly within a method, and the compiler is not clever enough to detect that it doesn't change after the creation of the expression.
I'd hate to have to build the expression by hand. Any brilliant ideas?
UPDATE: I ended up using the marvelous LinqKit to build a partial evaluator that will do the substitutions I want. The transform is only safe if you know that relevant references will not change, but it worked for my purposes. It is possible to restrict the partial evaluation only to direct members of your closure, which you control, by adding an extra check or two in there, which is fairly obvious on inspection of the sample code provided in the LinqKit.
/// <summary>Walks your expression and eagerly evaluates property/field members and substitutes them with constants.
/// You must be sure this is semantically correct, by ensuring those fields (e.g. references to captured variables in your closure)
/// will never change, but it allows the expression to be compiled more efficiently by turning constant numbers into true constants,
/// which the compiler can fold.</summary>
public class PartiallyEvaluateMemberExpressionsVisitor : ExpressionVisitor
{
protected override Expression VisitMemberAccess(MemberExpression m)
{
Expression exp = this.Visit(m.Expression);
if (exp == null || exp is ConstantExpression) // null=static member
{
object #object = exp == null ? null : ((ConstantExpression)exp).Value;
object value = null; Type type = null;
if (m.Member is FieldInfo)
{
FieldInfo fi = (FieldInfo)m.Member;
value = fi.GetValue(#object);
type = fi.FieldType;
}
else if (m.Member is PropertyInfo)
{
PropertyInfo pi = (PropertyInfo)m.Member;
if (pi.GetIndexParameters().Length != 0)
throw new ArgumentException("cannot eliminate closure references to indexed properties");
value = pi.GetValue(#object, null);
type = pi.PropertyType;
}
return Expression.Constant(value, type);
}
else // otherwise just pass it through
{
return Expression.MakeMemberAccess(exp, m.Member);
}
}
}
No there is no way to do this in C#. The compiler does not support capturing variables by value / const. Nor can you convert a non-const value into a const value at runtime in this manner.
Additionally the C# compiler only does constant folding during the initial compilation for known constant values. If it was possible to freeze a value at runtime into a constant it wouldn't participate in compiler constant folding because it happens at runtime.
The compiler doesn't do this type of "value caching". Constant folding is done at compile time for constants only, not for readonly fields and certainly not for local variables which do not have a known value at compile time.
You have to make this yourself, but it has to stay a closure reference (since the value is in fact not determinable at compile time, which is why it is likely to be put in the closure when the expression is built):
int x = magic(), y = moremagic();
int xy = x/y;
return i => i + xy;
x can't be a constant, because you're doing runtime magic to determine what it is. However, if you know that x and y don't change, try:
int x = magic(), y = moremagic();
int xOverY = x/y;
return i => i + xOverY;
I should also mention that even though the compiled IL code for i => i + (x/y) will show the division, the JIT compiler is almost certainly going to optimize this away.
One technique I used in vb2005 was to use a generic delegate factory to effect by-value closures. I only implemented it for subs rather than functions, but it could be done for functions as well. If extended in that way:
FunctionOf.NewInv()
would be a static function which would accept as parameters a function (described later), a T3, and a T4. The passed-in function should accept parameters of types T2, T3, and T4, and return a T1. The function returned by NewInv would accept one parameter of type T2 and call the passed-in function with that parameter and the ones given to NewInv.
The invocation would look something like:
return FunctionOf.NewInv((i,x,y) => i+x/y, x, y)
If you(like me) are creating some expression builder for SQL queries you may consirer the following: first create a class variable, make it a constant and then access it like this:
var constant= Expression.Constant(values);
var start = Expression.MakeMemberAccess(constant, values.GetMemberInfo(f => f.Start));
var end = Expression.MakeMemberAccess(constant, values.GetMemberInfo(f => f.End));
var more = Expression.GreaterThanOrEqual(memberBody, start);
var less = Expression.LessThanOrEqual(memberBody, end);

Categories

Resources