How does "char.IsUpper" (without parentheses) work? [duplicate] - c#

This question already has answers here:
C# method group strangeness
(2 answers)
Closed 9 years ago.
I just saw the following answer: Is there a better way to create acronym from upper letters in C#? and it has the following code:
string.Join("", s.Where(char.IsUpper));
How does the char.IsUpper work here? (Instead of x => char.IsUpper(x))

char.IsUpper is a method group, which itself takes a char and returns a bool, so it's a valid predicate for use with Where().
The code is referencing the method by name in much the same way as you would with any other method when specifying a delegate, instead of directly invoking it, so the parentheses aren't necessary.
The parentheses are necessary if you're wrapping it in a lambda expression x => char.IsUpper(x), because you're calling the method and returning the result, within the expression.

char.IsUpper refers to a method group which is passed to the Where function as a typed delegate via an implicit conversion which you can read in the Covariance and Contravariance in C#, Part Three: Method Group Conversion Variance article by Eric Lippert.

I believe char.IsUpper (without parentheses) evaluates to a reference to the method, that can be passed as a predicate. If you added parentheses, that would just immediately invoke the method and attempt to pass the result instead of passing the method itself.

Where<char> takes a Func<char, bool> as a parameter. By using x => char.isUpper(x), you are creating a new Func to be used by Where. However, the toUpper method, takes a char, and returns a bool. Therefore, it can be used directly as the parameter for Where.

Related

How does the compiler/runtime determine a lambda expression's type?

I was wondering how the the compiler/runtime determines a lambda expression's type?
For example, the following System.Linq Select extension method (not select query)
//var recordIds = new List<int>(records.Select(r => r?.RecordId ?? 0));
//var recordIds = new List<int>(records.Where(r => r != null).Select(r => r.RecordId));
var recordIds = new List<int>(records.Select(r => r.RecordId));
is defined as
Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, TResult>)
and so takes the lambda r => r.RecordId as a Func<TSource, TResult>.
How is the lambda's type determined, and once it is, is it simply cast to that type?
I was wondering how the the compiler/runtime determines a lambda expression's type?
It is rather complicated. Implementing this feature was the "long pole" for the version of Visual Studio that shipped C# 3 -- so every day that I was over schedule on this was a day that VS would slip! -- and the feature has only gotten more complicated with the introduction of covariance and contravariance in C# 4.
As others have noted, consult the specification for exact details. You might also read the various articles I've written about it over the years.
I can give you a quick overview though. Suppose we have
records.Select(r => r.RecordId)
where records is of type IEnumerable<Record> and RecordId is of type int.
The first question is "does IEnumerable<Record> have any applicable method called Select? No, it does not. We therefore go to the extension method round.
The second question then is: "is there any static type with an accessible extension method that is applicable to this call?"
SomeType.Select(records, r => r.RecordId)
Let's suppose that Enumerable is the only such type. It has two versions of Select, and one of them takes a lambda that takes two parameters. We can automatically discard that one. That leaves us with, as you note:
static IEnumerable<R> Select<A, R>(IEnumerable<A>, Func<A, R>)
Third question: Can we deduce the type arguments corresponding to type parameters A and R?
In the first round of type inference we consider all the non-lambda arguments. We only have one. We deduce that A could be Record. However, IEnumerable<T> is covariant, so we make a note that it could be a type more general than Record as well. It cannot be a type that is more specific than Record though.
Now we ask "are we done?" No. We still don't know R.
"Are there any inferences left to make?" Yes. We haven't checked the lambda yet.
"Are there any contradictions or additional facts to know about A?" Nope.
We therefore "fix" A to Record and move on. What do we know so far? We have:
static IEnumerable<R> Select<Record, R>(IEnumerable<Record>, Func<Record, R>)
We then say OK, the argument must be (Record r) => r.RecordId. Can we infer the return type of this lambda knowing that? Plainly yes, it is int. So we put a note on R saying that it could be int.
Are we done? Yes. Is there anything else we can make a deduction about? No. Did we infer all the type parameters? Yes. So we "fix" R to int, and we're done.
Now we do a final round that checks to make sure that Select<Record, int> does not produce any errors; for example, if Select had a generic constraint that was violated by <Record, int> we would reject it at this point.
We've deduced that records.Select(r=>r.RecordId) means the same thing as Enumerable.Select<Record, int>(records, (Record r) => { return (int)r.RecordId; } ) and that's a legal call to that method, so we're done.
Things get rather more complicated when you introduce multiple bounds. See if you can figure out how something like a Join works where there are four type parameters to infer.
I think the best place to look for such information is the language spec:
Section 7.15
An anonymous function is an expression that represents an “in-line”
method definition. An anonymous function does not have a value or type
in and of itself, but is convertible to a compatible delegate or
expression tree type. The evaluation of an anonymous function
conversion depends on the target type of the conversion: If it is a
delegate type, the conversion evaluates to a delegate value
referencing the method which the anonymous function defines. If it is
an expression tree type, the conversion evaluates to an expression
tree which represents the structure of the method as an object
structure.
The above explains the nature of lambda expressions, basically that they have no types by themselves, unlike say, an int literal 5. Another point to note here is that the lambda expression is not casted to the delegate type like you said. It is evaluated, just like how 3 + 5 is evaluated to be of int type.
Exactly how these types are figured out (type inference) is described in section 7.5.2.
...assume that the generic method has the following signature:
Tr M<X1…Xn>(T1
x1 … Tm xm)
With a method call of the form M(E1 …Em) the
task of type inference is to find unique type arguments
S1…Sn for each of the type parameters
X1…Xn so that the call
M1…Sn>(E1…Em)becomes
valid.
The whole algorithm is quite well documented but it's kind of long to post it here. So here's a link to download the language spec.
https://msdn.microsoft.com/en-us/library/ms228593(v=vs.120).aspx

C# method meaning [duplicate]

This question already has answers here:
What does the '=>' syntax in C# mean?
(7 answers)
Closed 8 years ago.
so I am looking at this C# method
if (IsInDesignMode)
{
// Only runs in design mode
_dataService.GetMachine(_machines[0].Machine.SerialNumber, (machine, error) => //<-- this is what I am confused about
{
SelectedMachine = new MachineViewModel(machine);
});
}
I understand the if() statement and the SelectedMachine = new MachineViewModel(machine); line.
But I am confused about the commented line.
_dataService calls a GetMachine method passing in _machines[0].Machine.SerialNumber param and (machine, error) => {}. It is not an "equal or less than" statement right?.
It kinda looks like a Javascript code to me...?
Does the method say,
If IsInDesignMode {
dataservice.GetMachine(machine serial number, machine error is new MachineViewModel)
}
Can any one explain what => { } this is? thank you very much!
The part you are asking about is an anonymous method that uses a lambda expression. It is commonly used in callbacks.
When you write this
(machine, error) => { SelectedMachine = new MachineViewModel(machine); }
you are making a function that has no name (and therefore cannot be reused by name, like a regular method). It is very convenient in situations when you need to produce a piece of callable code that needs to be used only once, e.g. in callbacks.
Note that the method does not have to be anonymous: you could make an equivalent named method. However, an since the anonymous method is built in the context of the method where it is used, the variables from the context are available to it. Your anonymous method assigns SelectedMachine, which is probably a property of your class. In the same way, anonymous methods can access local variables as well, which is a very powerful mechanism of combining together a state and a piece of code that operates on it.
To be more precise. It is an Anonymous method using lambda expression.
the sign you are asking '=> { }' is called lambda expression.
Usually it is used with Delegate type like func, Action, predicate and others.
Have a look on the above types to make yourself more clear.
It is a lambda expression. Have a look on this page for more info: http://msdn.microsoft.com/en-us/library/bb397687.aspx

What Is => Called and How Is It Used in C# [duplicate]

This question already has answers here:
C# Lambda ( => ) [duplicate]
(4 answers)
Closed 9 years ago.
I have seen => used in sample code, but I don't know what this operand is called. Because the term is just symbols, Google search is not very helpful.
Here is an example of its use:
var rolesAllowed = rolePermission.Where(permission => permission.Permissions.Any(p => Demand.HasFlag(p.Type))).ToList();
This question is different from the ones so brazenly marked as "duplicate". I was looking for the name of the expression so I could research how to use it. The so-called duplicate item was for someone who already knew that => was called a lambda expression.
I want to thank the people who took the time to read and understand the question, and post a quality response.
It is called Lambda operator
To create a lambda expression, you specify input parameters (if any)
on the left side of the lambda operator =>, and you put the expression
or statement block on the other side. For example, the lambda
expression x => x * x specifies a parameter that’s named x and returns
the value of x squared.
Lambda expressions use special syntax. They allow functions to be used as data such as variables or fields. The lambda expression syntax uses the => operator. This separates the parameters and statement body of the anonymous function.
The => operator can be read as "goes to" and it is always used when declaring a lambda expression.
That is used to for lambda expressions. Essentially what that the Where function takes in is another function that iterates through the collection. The left side of the => defines the parameters and the right side is the actual function that gets run.
It is called lambda operator and it's the part of the lambda expression syntax.
Lambda expressions are very concise way to create anonymous methods.
Anonymous method example:
button1.Click += delegate(System.Object o, System.EventArgs e)
{ MessageBox.Show("Click!"); };
The same code, but this time using lambda expression:
button1.Click += (o,e) => MessageBox.Show("Click!");
As shown, this syntax is a
great shorthand notation for authoring anonymous methods, where a stack of arguments can be passed
into a group of statements for processing. Any method in the .NET platform that takes a delegate object
as an argument can be substituted with a related lambda expression, which will typically simplify your
code base quite a bit.
This is the lambda operator, it creates a lambda expression, which is like an anonymous method.
=> is a lambda operator, check the link to read more.
Also check this answer for more details.

What does SomeMethod(() => x.Something) mean in C#

(Note the code is an example)
I have the following syntax:
SomeMethod(() => x.Something)
What do the first brackets mean in the expression?
I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
What do the first brackets mean in the expression?
It's the lambda syntax for a method that takes no parameters. If it took 1 parameter, it'd be:
SomeMethod(x => x.Something);
If it took n + 1 arguments, then it'd be:
SomeMethod((x, y, ...) => x.Something);
I'm also curious how you can get the property name from argument that is being passed in. Is this possible?
If your SomeMethod takes an Expression<Func<T>>, then yes:
void SomeMethod<T>(Expression<Func<T>> e) {
MemberExpression op = (MemberExpression)e.Body;
Console.WriteLine(op.Member.Name);
}
The () is an empty argument list. You're defining an anonymous function that takes no arguments and returns x.Something.
Edit: It differs from x => x.Something in that the latter requires an argument and Something is called on that argument. With the former version x has to exist somewhere outside the function and Something is called on that outside x. With the latter version there does not have to be an outside x and even if there is, Something is still called on the argument to the function and nothing else.
It's a lambda expression. That is, it's a way to create an anonymous function or delegate.
The general form is:
(input parameters) => expression
If you have
() => expression
then you have created a function that takes no arguments, and returns the result of the expression.
C# uses type inference to figure out what the types of the values are, and it captures local variables (like your "x" variable) by means of a lexical closure.
I assume x is declared in somewhere inside your method, if yes, you can compare this lambda expression with a delegate that has no paramaters and return the type of x.someproperty
delegate{
return x.someproperty;
}
that is the same as:
() => x.someproperty
the () mean that this method doesn't take any parameters.
for example, if you assign a normal event handler using a lambda expression, it would look like this:
someButton.Click += (s, e) => DoSomething();
See also the following two blog posts that discuss exactly your second question and provide alternative approaches:
How to Find Out Variable or Parameter Name in C#?
How to Get Parameter Name and Argument Value From C# Lambda via IL? (Or "How NOT to Use .NET Linq Expressions in Order to Get Parameter Name and Argument Value From C# Lambda?")
To get the name of the property you need SomeMethod to have an argument of the type of System.Linq.Expressions.Expression<System.Func<object>>. You can then go through the expression to determine the property name.

Confused about LINQ parameters

I am trying to understand LINQ and become confident at using it. What I am struggling with are the parameters asked for. Example:
var sortedWords = words.OrderBy(a=>a.Length)
words is an array collection. OrderBy's intellisense says:
Func<string, TKey> keyselector
A func executes a method, and a string is the value, TKey a key.
In the example http://msdn.microsoft.com/en-us/vcsharp/aa336756.aspx#thenBySimple (ThenBy - Comparer), we compare length by saying a => a.Length. I understand that syntax, but how is that related to what the intellisense is asking for?
I tend to find the method signature and intellisense unreadable because of all the generics.
Thanks.
The type (as displayed by Intellisense) makes sense if you understand the nature of lambda expressions in .NET/C#. Otherwise, it can indeed seem a bit strange to the newcomer. Begin by considering that the type of keySelector, Func<TSource, TKey> is simply a delegate. Before C# 3.0, you would call such a method by passing a delegate as a parameter, for example:
IEnumerable<string> sortedWords = words.OrderBy(new Func<string, int>(mySelectorMethod));
where mySelectorMethod is the name of an ordinary method which takes a string as a parameter and returns an int. (As a side point, I suppose you could use anonymous delegates, but let's not go there for now.) Also, note that this example is purely illustrative, as LINQ is almost always used with .NET 3.5/C# 3.0 (though I believe it can be used with either/both .NET 2.0/C# 2.0 - someone correct me if I'm wrong). Since C# 3.0, methods can be defined inline as lambda expressions, which are intended to be used in precisely such circumstances as these. Read over the MSDN article on lambda expressions (linked above) if you want to get a proper introduction, but here I will simply describe the use in this specific context. As you state, your code (in C# 3.0) is something like the following:
var sortedWords = words.OrderBy(a => a.Length);
The part of the expression that is a => a.Length is the lambda expression, which is really just shorthand for declaring a function inline. The syntax of lambda expressions is quite simple for the most part; to the left of the => the arguments are specified, generally in the form (arg1, arg2, arg3), but since there's only one in this case you can omit the brackets. To the right of the => is the expression that is the return value of the function (lambda expression more accurately). Alternatively you can enclose actual code with a return statement within { and } though this is usually unnecessary. What I believe the C# compiler does is recognises the parameter passed to OrderBy as a lambda expression and then compiles it into a function and creates and passes the delegate for you. Note that lambda expressions can also be converted to System.Linq.Expressions.Expression objects (accessible expression trees) instead of delegates, but this is a much less common usage. Anyway, there's a lot going on behind the scenes here, but hopefully this should at least clarify why the type is Func<TSource, TKey> and how it relates to the lambda expression. As I said, read up on MSDN if you want a deeper understanding of LINQ/lambdas/delegates...
a => a.Length
I understand that syntax, but how is that related to what the intellisense is asking for?
This chunk of code is a lambda expression. A lambda expression is a handy way of generating an Anonymous method (in this case), or a System.Linq.Expressions.Expression . Let's break it down by parts.
The most noticeable feature is the =>, which seperates parameters from a method body.
On the left side of the =>, there is a symbol: a. This is the declaration of a parameter for our anonymous method. The compiler is aware that we are calling OrderBy(), and that OrderBy requires a Func<string, object>. The parameter for such a function is a string, so the compiler determines that a must be a string. The only thing the programmer needed to provide is a name.
On the right side of the =>, there is method body. Since this is a one-liner, the return keyword is implied. The IDE provides intellisense against a as a string, which allows you to use the Length property.
Now, consider this C# 2.0 ...
IEnumerable<string> sortedWords =
Enumerable.OrderBy(words, delegate(string a) {return a.Length;});
With the C# 3.0
IEnumerable<string> sortedWords = words
.OrderBy(a => a.Length);
I think the IntelliSense is actually quite useful, especially for generic methods that take Func<..> type as an argument, because you can see the types and types guide you to understand what the method might do.
For example, the arguments for OrderBy are IEnumerable<string> as a 'this' argument, which means that we have some input containing collection of strings. The first argument keySelector has a type Func<string, TKey>, which means that it is some lambda expression you provide that specifies how to get TKey from string.
This already suggests that the method will probably enumerate over all the items (strings) in the collection and it can use the keySelector to get value of type TKey from every element in the collection. The name TKey already suggests that it will use this value to compare the elements (strings) using this calculated key. However, if you look at the other overload that takes IComparer<TKey> then you can be sure about this - this argument specifies more details about how do you want to compare two values of type TKey, so the function must compare the elements using this key.
... this kind of thinking about types takes some time to get used to, but once you'll learn it, it can be extremely helpful. It is more useful in "functional" style of code, which often uses a lot of generics and lamdba expressions in C# 3.0 (and similar things in functional languages like F# or others)
I never really worry about the Intellisense, to be honest. It was messing me up early in my Linqage. As I spent more time with generics and expressions, it started to make sense, but up until then I just pumped in the syntax.
What it wants is a lambda expression that tells Linq what to look for in order to sort your collection.
I feel you, my brother, hang in there and it will make sense very soon.
OrderBy() takes a delegate for a function that accepts a single parameter (in your case, a string) and returns a value of the type that is substituted for TKey. It may be that the parameter type (string) was already determined since you called the method on an IEnumerable<string> but the delegate type will only be resolved as Func<string, int> after it infers it from the lambda expression when it is fully specified (i.e., a => a.Length). If you haven't given the parser any clues as to what you want as a sort key, it'll just show TKey in IntelliSense until it can determine the intended type.

Categories

Resources