do all anonymous functions need to be typed with delegate keyword? for example we have a Customer class,
delegate(Customer a)
{return a.name == "Michael";}
Is this anonymous function
(Customer a)
{return a.name == "Michael";}
a function or a delegate or both?
do all lambda expression also Predicate delegate by default? for example, we have a List of Customer, which is listCustomers, if we want to use TrueForAll function to see whether all customers called "Michael", we can just type as:
listCustomers.TrueForAll(x => x.name == "Michael);
But TrueForAll takes Predicate as parameter, as we know Predacate is a delegate, which means "x => x.name == "Michael" is also a Predicate delegate by default?
Forms of anonymous delegates:
// A: C# 2.0... No one uses it in new developments since years
delegate() { }
// B: C# 3.0 and above
() => { }
Why can I set an anonymous delegate to a given delegate?
Action a1 = () => Console.WriteLine("hello world");
Action<int> a2 = number => Console.WriteLine(number);
Func<bool> f1 = () => true;
This is called delegate type inference.
In summary, if the right side of an assignment fulfills the signature of the left side (i.e. the delegate type), the right side is infered as the type of the left side. This is also true for method parameters.
In the other hand, it's not the same a lambda expression than a delegate with lambda syntax:
Expression<Action> expr1 = () => Console.WriteLine("hello world");
Action a1 = () => Console.WriteLine("hello world");
The first is an expression tree, which is a data structure similar to an abstract syntax tree that can be used to extract info from the epxression and its childs, while the later is a delegate.
Expression trees can be compiled into delegates:
Action a2 = expr1.Compile();
a2();
Further reading
Lambda expressions
Delegate Type Inference in C#
Related
I can print a lambda expression like this
Expression<Func<double,double>> expr = x => x * x;
string s = expr.ToString(); // "x => (x * x)"
However if
Func<double, double> function = x => x * x;
Then how can I generate the Expression<Func<double,double>> to produce the same result ? Expression constructor is internal and there is no implicit conversion between Func types and Expression of them.
You can't.
When you write:
Expression<Action<int>> e = x => Console.WriteLine(x);
The compiler emits (simplified):
ParameterExpression parameterExpression = Expression.Parameter(typeof(int), "x");
MethodInfo method = typeof(Console).GetMethod("WriteLine", new[] { typeof(object) });
MethodCallExpression body = Expression.Call(null, method, parameterExpression);
Expression<Action<int>> e = Expression.Lambda<Action<int>>(body, parameterExpression);
See how it actually emits code which re-creates the expression tree at runtime?
In contrast, when you write:
Action<int> a = x => Console.WriteLine(x);
The compiler emits (simplified)
internal void GeneratedMethod(int x)
{
Console.WriteLine(x);
}
...
Action<int> a = new Action<int>(GeneratedMethod);
See the difference? The runtime simply isn't able to take a compiled method and create an expression tree for it.
The only way that expression trees get constructed is using the methods on the Expression class to build it up out of its various parts. If you use a lambda, the compiler cleverly emits code which does this at runtime. However you can't start with a compiled method.
See the examples on SharpLab.
I would like to create a lambda expression and invoke it immediately and I would like to avoid creating a delegate; a trivial example1:
int i = (() => 42)();
This produces the error:
CS0149 Method name expected
There are two workarounds:
Declare a (local) method:
int Return42() => 42;
int i = Return42();
Create a delegate:
int i = ((Func<int>)(() => 42))();
It is possible to create and immediately invoke a lambda expression without creating a delegate and without naming it? And if possible, how can one create such a lambda?
1. In reality it is an async Task that I would like to use instead of Task.ContinueWith (I tried to follow what Stephen Cleary said: you should strive to replace ContinueWith with await); e.g:
Task<int> future = (async () =>
(await RetrieveLookupFromFarAway())["42"].First())();
With RetrieveLookupFromFarAway something like:
async Task<ILookup<string, int>> RetrieveLookupFromFarAway()
{
await Task.Delay(1000);
return Enumerable.Empty<int>().ToLookup((x) => x.ToString());
}
The concept of a lambda expression only exists as source code. It doesn't even have a type in itself (just like the null literal doesn't have a type). It has to be converted to either an expression tree or a delegate: that's what exists as far as the IL and the CLR are concerned. The compiler has to emit code to create something, and you need to tell it which type you want that to be.
The compiler doesn't play favourites in terms of delegate types: while it could "know" about Func<T> and use that as a default delegate type for a lambda expression with no parameters, it doesn't.
The closest you'll get to what you want is to have a convenience method that you can call accepting a Func<T>, which could either just return the function, or execute it and return the result. For example:
public static Func<T> CreateFunc<T>(Func<T> func) => func;
public static T ExecuteFunc<T>(Func<T> func) => func();
Then you can call it as:
CreateFunc(() => 42)();
or
ExecuteFunc(() => 42);
I'm trying to pass a Predicate to a function but it has no input. I'm actually trying to delay the computation until the call is made.
Is there a way to use c# Predicate type for that? If not why.
I know a way to do this with Func
Func<bool> predicate = () => someConditionBool;
But I want to do this:
Predicate<> predicate = () => someConditionBool;
If it's just a readability problem, then you can create your own delegate which returns boolean and don't have any parameters:
public delegate bool Predicate();
And use it this way
Predicate predicate = () => someConditionBool;
NOTE: You should keep in mind that everyone is familiar with default Action and Func delegates which are used in .NET, but Predicate is your custom delegate and it will be less clear at first time for average programmer.
Is there a way to use c# Predicate type for that? If not why?
Looking at the signature of Predicate<T> is shows that it requires an argument or parameter:
public delegate bool Predicate<in T>(T obj)
So the quick answer here would be no. Because you have no parameters in your anonymous function.
But if you play a little around you can give the predicate some irrelevant object which it will not use anyway, like an alibi parameter:
Func<bool> predicate = () => 1 == 1;
Predicate<object> predicate2 = (x) => 1 == 1;
and the call would look like this:
Console.WriteLine(predicate());
Console.WriteLine(predicate2(null));
And this compiles and returns the correct result
I am trying to create a method to process a certain query. I follow an example posted on the Nest repository (line 60), but still the MatchAll is not recognized by the compiler and if I try to build the solution, the error that shows is:
Operator '??' cannot be applied to operands of type IQueryContainer and lambda expression
This is my method so far:
public void ProcessQuery(IQueryContainer query = null)
{
var searchResult = this._client.Search<T>(
s => s
.Index(MyIndex)
.AllTypes()
.From(0)
.Take(10)
.Query(query ?? (q => q.MatchAll())) // Not valid
.SearchType(SearchType.Scan)
.Scroll("2m")
);
}
The type of a lambda expression can either be converted to an Expression or to some delegate type, but most likely not to IQueryContainer. Lambda expressions themselves do not have a type and need specific context for that automatic conversion, which you can give e.g. by using an appropriate delegate type constructor. But again: I don't believe an interface on one side of ?? and a lambda expression on the other makes any kind of sense.
Thanks to the comment of #Mrinal Kamboj and the answer of #Wormbo, I found my own answer:
I changed the argument type to QueryContainer and if the argument is null, a new QueryMatchAll query is created, this works for me:
public void ProcessQuery(QueryContainer query = null)
{
var searchResult = this._client.Search<T>(
s => s
.Index(MyIndex)
.AllTypes()
.From(0)
.Take(10)
.Query(query ?? new MatchAllQuery()) // Now works
.SearchType(SearchType.Scan)
.Scroll("2m")
);
}
I know that you cannot return anonymous types from methods but I am wondering how the Select extension method returns an anonymous type. Is it just a compiler trick?
Edit
Suppose L is a List. How does this work?
L.Select(s => new { Name = s })
The return type is IEnumerable<'a> where 'a = new {String Name}
The type is actually defined by the caller, so it's in the scope of the calling function - neatly avoiding the issue of "returning" an anonymous type.
This is accomplished by generic type inference. The signature for Select is Select<Tsource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>. The IEnumerable<TSource> is, obviously, the source collection. The Func<Tsource, TResult> transformation function is where the compiler can use type inference to declare an anonymous type.
In other words, in order to pass a Func<Tsource, TResult> to Select, you - the caller - must define TResult. Which means Select isn't returning an anonymous type defined by it - but by you.
To emulate this, you just have to get the caller to define the type:
TResult ReturnAnonymousType<TResult>(Func<TResult> f) {
return f();
}
Console.WriteLine(ReturnAnonymousType(
() => return new { Text = "Hello World!" } // type defined here, before calling
);
Well, it's normal type inference for generic method type arguments. For instance:
List<string> x = new List<string>();
// The compiler converts this:
x.Select(y => y.Length);
// Into this, using type inference:
Enumerable.Select<string, int>(x, y => y.Length);
The same would be true if x were a list of some anonymous type, or if the inferred return type of the lambda expression were an anonymous type. Don't forget that even though you can't explicitly state the type of a variable which uses an anonymous type, it still does have a definite type, known to the compiler.
From comment: " So how would I go about implementing a similar method"
All you need here is any generic method:
public List<T> Foo<T>(T template) { // doesn't actually use "template"
return new List<T>(); // just an example
}
then you can have:
var list = Foo(new {Bar=1});
The compiler provides the <T> via generic type inference.
A bit cheeky, but you can even do it without actaully ever creating an instance of the anon-type:
public List<T> Foo<T>(Func<T> func) { // doesn't actually use "func"
return new List<T>(); // just an example
}
var list = Foo(() => new {Bar = 1});
Again, the is provided by the compiler via the return value of the lambda.
The return type of Select is generic, and it is inferred from the lambda provided in most situations.
For example:
List<int> list = new List<int<();
var val = list.Select(x => new {value = x, mod = x % 10});
The return value of the select is based on the anonymous type I defined, and is extrapolated from the lambda, to a delegate, to the Select function. The Select function in this case does not know about or care about the particular anonymous type, as it is a generic type from its perspective.