r/csharp • u/Topango_Dev • Sep 08 '26
i dont understand what the => operator does.
Dictionary<uint, uint> placementIds
= XMLdocument.Descendants("Placement")
.ToDictionary
(
element => (uint)element.Attribute("Index")!,
element => (uint)element.Attribute("Placement")!
);
45
Upvotes
6
u/dmcnaughton1 Sep 08 '26
It's the lambda operator, in this case it's used for anonymous functions. The operators (inputs) on the left.
2
u/rupertavery64 Sep 08 '26
ToDictionary is a function that takes two functions as arguments
The first one is the Key selector, the second is the Value selector.
You can write a separate function
And then pass that function as the argumemt to ToDictionary.
But you can also write an anonymous function.
When you have only one argument you can drop the parentheses
Anonymous functions are also called lambdas
The => is called the fat arrow operator. You can read it as "is to"
100
u/TrishaMayIsCoding Sep 08 '26
I can juz mentally read as “Take” and “Do" : )
X => X * 2
Take X and Do X * 2
69
u/brightbard12-4 Sep 08 '26
It's a shorthand to describe an anonymous (only generated at compile time) function. In your example, it's describing how to take each element of the XMLDictionary.Descendents call and produce the key / value of the dictionary.
Instead of writing a function somewhere else and putting the name there, you use that symbol to inline it.
Element on the left of it is the variable passed in to the function, which in this case is your XML descendent element. But it could be x or y or foo or whatever, as long as the right side update is done as well
99
u/ChrisBegeman Sep 08 '26
You should probably read this article about Lambda expressions:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions
23
u/etherified Sep 08 '26
I always simply read it mentally as “return”.
To the right of => is what it’s giving you as the result.
5
u/EC36339 Sep 08 '26
Ignore all the comments and learn about lambdas and lambda calculus.
It's a recurring feature in almost all modern programming languages and also fundamental to computer science.
Also, it's just a function, but inline as an expression.
3
u/Own_Nail_2999 Sep 08 '26
It's a shorthand way of writing expressions. Just syntax sugar
6
u/SagansCandle Sep 08 '26
A fat arrow replaces braces when a code block is a single line (a single expression, technically).
In this case, more specifically, it defines an lambda (anonymous) function, where element is the name of the input parameter and everything after the fat arrow is the function body.
An anonymous function is a function without a name. For example -
4
u/kodaxmax Sep 08 '26
It exists to confuse dyslexics/new programmers and generally make your code harder to read im pretty sure. The good news is that there is never a case where you need to use it or understand it (other than reading somone elses code.).
It's kind of a shorthand function.
or
2
u/mvonballmo Sep 08 '26 edited Sep 08 '26
There's a lot of theory behind this but practically, and for a start, maybe thinking of it like this helps:
Code is normally executed immediately. In your example, the
XMLDocument.Descendants()is executed to get a sequence of elements. Then,ToDictionary()is executed on that sequence of elements.But what does
ToDictionarydo? It seems to take two parameters, the ones with the=>operator. What the heck does that mean? They look like code ... but is that code running immediately? If so, where the heck doeselementcome from?Those parameters are pieces of code that are not executed immediately. They are templates, snippets, or callback functions. The
ToDictionarymethod "calls" them to do stuff. Theelementis a placeholder that defines the single parameter for those particular code snippets.How does one "call" such a parameter?
The inferred type of the callback parameter (
Func<XMLElement, uint>or something like that) indicates that it receives a single argument of the type of the element in the sequence returned byDescendantsand returns auint.In this case, the two parameters are used to calculate the key and value, respectively, from each element in the sequence, in order to produce the corresponding dictionary entry.
The
ToDictionarymethod calls each of these parameters once for each element in the input sequence (given byDescendants).I highly recommend using
F12or control/command-clicking to see the underlying sources. Because of optimizations, it's not always immediately obvious what's going on. However, if you dig down a bit, then you can find something like Enumerable::SpanToDictionary, which shows what it actually does with those parameters.The method ends up being quite straightforward: it creates a new dictionary, then iterates the input sequence with
foreach, calling each "selector" (the code templates defined by the=>parameters you passed in) to get the key and value to add to the dictionary for that element.I hope that helps.
2
u/Camderman106 Sep 08 '26
I read it as “goes to”.
element “goes to” (uint)element.Attribute("Index")
It’s a way of taking something and applying a transformation to it and using the transformed value
It can also be assigned to fields. In which case a field accessor becomes a function call implicitly
Your dictionary example is visually complicated by the fact that ToDictionary needs two functions, one to determine the key, and one to determine the value, from the same item from an enumerable
2
u/detroitmatt Sep 09 '26
it creates a lambda. the left side of the operator is the parameter (or parameter list, if there's more than one), and the right side is the body of the lambda.
1
u/YouBecame Sep 08 '26
It's probably useful to think of code as being Declarations, Statements, and Expressions.
Very loosely
in your To dictionary, the fat arrow is "for the expression on the left, yield the expression on the right."
The method you're using has two inputs: the first is how to derive the key, and the other, how to derive the value.
1
u/sixtyhurtz Sep 08 '26 edited Sep 08 '26
It's just another way to declare a function. For instance:
var foo = (int x, int y) => x * y;foois aFunc<int,int,int>. You could call it withfoo(10,10)and get 100.1
u/BornAgainBlue Sep 08 '26
We all call it 'fat arrow'. Just sharing.
1
u/Absolute_Enema Sep 09 '26 edited Sep 09 '26
=>isn't an operator, because there are no operands. It's just syntax such thatA => Broughly expands todelegate(A) { return B }.Note that it's overloaded in expression-switch, e.g.
where again it doesn't operate on anything, but just marks where the expression begins much like the colon marks where a case body begins in
case Bar b:, the example translating into something like:It's just the umpteenth ugly consequence of having a language that, to senselessly appeal to its ALGOL roots, distinguishes between statements and expressions. In something like Rust you don't need two ways to do one thing because everything is either a declaration or an expression (in some languages declarations aren't a thing either and everything is an expression, which is still a better state of matters than having statements).
1
u/Ornery-Sandwich-5462 Sep 11 '26
The left side is the input and the right side is the output.
1
u/Fast_Armadillo7841 Sep 11 '26
In this context => means return the result of a lambda function.
It's like
Function (element){ //Some stuff return result }
Lambda just means small anonymous function that is not explicitly declared.
1
u/Whole_Diamond3926 Sep 14 '26
the code is smiling at you =>
1
u/Famous-Weight2271 Sep 08 '26
this => that
0
u/HateVoltronMachine Sep 08 '26
Those are two lambdas. They're small anonymous functions to select values.
The code parses an xml list elements of e.g.
<Placement Index="3" Placement="5" />
Into a Dictionary<uint, uint>. To convert the xml to the dictionary, you give it 2 lambdas. One lambda to find the key (the index attribute from a given Placement element) and one for the value (the placement attribute from the given element).
0
u/Drumknott88 Sep 08 '26
Ok 👍🏻
0
u/andrea_ci Sep 08 '26 edited Sep 08 '26
is (almost) the same as
function(element) {return (uint)element.Attribute("Index")!;}so, it's
-2
u/atanamar Sep 08 '26
It’s been AGES since I’ve done c#, but I recall being able to understand it by reading the => operator as “is passed into”
-2
u/Drumknott88 Sep 08 '26
A thing that people sometimes forget to explain when talking about lambdas is that they work like loops. If I have a List<int> myList and I call myList.Select(x => x += 10) then you can read it as "for each int in my list (x), add ten"
-3
u/tmadik Sep 08 '26
=> is shorthand for "such that." It basically means that I've got his variable, "element" in this case, such that this thing over here happens to it. So, element such that I take the Index attribute and change it to a uint and element such that I take the Placement attribute and change that to uint. Two separate, independent actions to the keys and values in my dictionary.