Not clear about how this symbol => is being used in the code.

Ronald Rex 1,666 Reputation points
2021-11-14T19:33:27.503+00:00

I am watching this video tutorial at watch
and I am a little confused about what the expression public override string ToString()=> JsonSerializer.Serialize<Product>(this); does in the following code block. The => is referring to a lambda expression, correct? Thank You !!!

public class Product
    {
        public string Id { get; set; }
        public string Maker { get; set; }
       [JsonPropertyName("img")]

        public string Image { get; set; }
        public string Url { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int [] Ratings  { get; set; }

        public override  string ToString()=> JsonSerializer.Serialize<Product>(this);


    }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,772 questions
0 comments No comments
{count} votes

Accepted answer
  1. SMil 386 Reputation points
    2021-11-14T21:43:05.617+00:00

    This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...}. But they have some important differences. For example, they do not bind their own values of this .

    Arrow functions are part of the ECMAscript 6 specification. They are not yet supported in all browsers, but they are partially or fully supported in Node v. 4.0+ and in most modern browsers in use as of 2018. (I’ve included a partial list of supporting browsers below).

    An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.

    A Note on How this Works in Arrow Functions
    One of the most handy features of an arrow function is buried in the text above:

    An arrow function... lexically binds the this value (does not bind its own this...)

    What this means in simpler terms is that the arrow function retains the this value from its context and does not have its own this. A traditional function may bind its own this value, depending on how it is defined and called. This can require lots of gymnastics like self = this;, etc., to access or manipulate this from one function inside another function.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.