What is the advantage of using "Expressions of Functional Functions and Properties",

I have seen many using this new feature, but what is the advantage of using these expressions?

Examples :

public override string ToString() => string.Format("{0}, {1}", First, Second); public string Text => string.Format("{0}: {1} - {2} ({3})", TimeStamp, Process, Config, User); 

This question is different from this because I am not just asking if performance and efficiency are changing, but also about the difference between compiled code (IL code), and if this is best practice and should be used in the real world.

This question is also not off topic , because I ask for real work experience in the enterprise, and not for recommendations. Therefore, do not recommend, but explain why you would like or why you would not use this feature and what impressions you have with it!

+6
source share
3 answers

A body expression provides only a compact and clean way to declare a readonly property. In terms of performance, you write this:

 public bool MyProperty { get { return myMethod(); } } private bool myMethod() {return true;} 

or that:

 public bool MyProperty => myMethod(); private bool myMethod() {return true;} 

There is no difference because it is translated into IL in the same way.
But pay attention to this thing: body expression is a feature available for Deafult on Visual Studio 2015 and newer, but if you want to use in the old version of VS, you need to install C # 6.0 from nuget

+4
source

It provides better readability and preserves some space in the code. It is better.

+2
source

Answering one of my questions. I tested if the IL code matches the following results:

 static void Main(string[] args) { Console.WriteLine(MyClass.GetTexted); } class MyClass { private static string dontTouchMe = "test"; public static string GetTexted { get { return dontTouchMe + "1"; } } //public static string GetTexted => dontTouchMe + "1"; } 

... will generate the same IL code:

 00993376 call [random value] 0099337B mov dword ptr [ebp-40h],eax 0099337E mov ecx,dword ptr [ebp-40h] 00993381 call 71886640 00993386 nop } 00993387 nop 00993388 lea esp,[ebp-0Ch] 0099338B pop ebx 0099338C pop esi 0099338D pop edi 0099338E pop ebp 0099338F ret 

The [random value] is the only code that has changed, which makes sense as it changes every time it compiles.


I am still a student at school, so I can only answer other questions from my point of view (which is not a type of enterprise):

  • "Expression Bodied Functions and Properties" really seems to be a good practice because of its more compact and readable code. (thanks to @Wazner and @MacakM )

  • It also makes sense to use them because they look more modular and similar to OOP code.

+2
source

Source: https://habr.com/ru/post/1011849/


All Articles