How to store all ctor parameters in fields

  • A+
Category:Languages

I'm learning C# and a thought came up when coding. Is it possible to automaticly store parameters from a constructor to the fields in a simple way without having to write this.var = var on every variable to store them?

Example:

class MyClass {     int var1;     int var2;     int var3;     int var4;     public MyClass(int var1, int var2, int var3, int var4){         this.var1 = var1;         this.var2 = var2;         this.var3 = var3;         this.var4 = var4;     } } 

Is there a way to avoid writing this.varX = varX and save all the variables to the fields if the names are the same?

 


No, there is no way to do this more easily in the current version of C#. There was a new feature in the C# 6.0 prereleases called Primary Constructors to solve this, but it was removed before the final release. https://www.c-sharpcorner.com/UploadFile/7ca517/primary-constructor-is-removed-from-C-Sharp-6-0/

Currently, I believe the C# team are working on adding records to the language: https://github.com/dotnet/roslyn/blob/features/records/docs/features/records.md - this should make working with simple data classes much simpler, as in F#

Comment

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