Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store all ctor parameters in fields

Tags:

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?

like image 444
Fredrik Persson Avatar asked Feb 22 '19 10:02

Fredrik Persson


2 Answers

If you define your variables first, you can use visual studios' "Quick actions" tool to generate a constructor for you; this gives you a choice of the currently-defined class fields to include.

using this will insert a constructor class with all your selected fields as parameters, and it will assign the values to the fields.

This will not reduce the amount of code, but it will cut back on the amount of typing you need

like image 146
ThisIsMe Avatar answered Sep 22 '22 19:09

ThisIsMe


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#

like image 40
Jonas Høgh Avatar answered Sep 24 '22 19:09

Jonas Høgh