Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - constant property is equivalent to lambda expression?

I picked up C# again, came back after a long work in Java, and as you may expect, I got very interested in properties(oh the Java burden), therefore I started to explore them a bit and came up with this.

private static float Width {
    get { return 0.012f; }
}

After a bit of tinkering, I realized this works too(lambda expression?).

private static float Width => 0.012f;

Now please help a fellow Java developer here to understand what is exactly the difference? What the former can do that the latter cannot and vice versa.

like image 490
julian Avatar asked Nov 20 '15 10:11

julian


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C full form?

Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

what is exactly the difference?

Both ways define a getter only property. The latter simply uses C# 6's new feature called "Expression Bodied Members", specifically these are "Expression Bodied Properties", which allow you to use the fat arrow syntax and are merely syntax sugar.

If you look at what the compiler generates, you'll see:

private static float Width
{
    get
    {
        return 0.012f;
    }
}

Which is identical to your getter only declaration.

These can also be applied to one-liner methods as well:

public int Multiply(int x) => x * x;
like image 63
Yuval Itzchakov Avatar answered Sep 25 '22 02:09

Yuval Itzchakov


This is a simplification of the language under C# 6.0 and are called 'Expression Bodied Functions / Properties'.

The idea is to simplify the syntax and allow you to set values for functions and properties in a shorter format.

Visual Studio magazine has an article on it here: https://visualstudiomagazine.com/articles/2015/06/03/c-sharp-6-expression-bodied-properties-dictionary-initializer.aspx

like image 37
Karl Gjertsen Avatar answered Sep 22 '22 02:09

Karl Gjertsen