Difference between readonly keyword/Expression-bodied members in c#?, which is better?

  • A+
Category:Languages

In c# readonly members can be reduced to readonly auto properties/expression-bodied members for immutable members is expression-bodied members are better then using readonly keywords?

Using readonly keywork:

public static readonly string  COMPANY_NAME= "XYZ"; 

Using Expression-bodied Members:

public  static  string  COMPANY_NAME => "XYZ"; 

I have come across various forums and solution that suggest expression bodied members for short hand use, and i could not find how it differs in performance.

 


First, you should use const with string constants, not readonly. You should use the latter only for objects requiring a constructor call to construct them.

There is a side note to this though, as stated in comments, you should be aware that constants can be optimized even across assemblies (so your library constants can also be evaluated as constants on compile time by the referenced library). That would mean that with minor version updates, you could end up with another constant value in the assembly than in your library. In such cases you should keep using static readonly.

Second, there is a huge difference between static readonly fields and static properties. The static properties will get evaluated each and every time you call it. The static readonly is slightly optimized, since it does only do a single assignment.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: