My question is what the => characters are used for in C#, I have seen it in a method to access the device's light sensor. This is the method
private void _lightSensor_ReadingChanged(LightSensor sender, LightSensorReadingChangedEventArgs args)
{
_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
Lux = args.Reading.IlluminanceInLux;
});
Debug.WriteLine("Lux: {0}", Lux);
}
Thanks.
In C# the operator
=>
is known as the lambda operator.It is used to create a
Func<>
,Action<>
orExpression<Func<>>
as needed.in your case
It is equivalent to a method similar to this
To the left of
=>
it is the list of arguments, in this case empty, and to the right is the block of code to be executed.Since there is only a pair of empty parentheses on the left, the method has no parameters and since the code block does not return anything, its return type will be
void
Lambda operator =>
Operator documentation = > in Spanish.
It's a lambda expression or operator, the same thing my colleague said up there, it's part of the functional programming operators in C# and other languages, it's a shorter way of writing a function, plus it allows you to create simpler rules, that is , contributing to what has already been mentioned in this, I tell you that you can validate objects, you can declare axioms that will later be executed.
So if you realize you can do that with these kind of functions, instead of using a bunch of
if-else
you can make a collection of functions that validate the state of an object. avoid spaghetti code.This is for you to see the potential that this type of programming has and its usefulness, however, it is just an example of everything that can be achieved using this.
I'm not trying to explain this whole paradigm to you in a single example, that would be impossible, but I'll tell you with this example a usefulness and value that you can achieve if you learn it.