0
public class Class 
{
    string field1;
    int field2;
    bool field3;

    public Class(string field1, int field2, bool field3)
    {
         this.field1 = field1;
         this.field2 = field2;
         this.field3 = field3;
    }
}

Is there any way to do this in a more clean/less redundant way? This gets a bit annoying when you have a lot of parameters.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
DudeManGuy
  • 123
  • 2
  • 12
  • 1
    if you name the fields different i.e. `_field1` you can get rid of `this.` → `_field1 = field1;` – Maximilian Ast Aug 08 '20 at 10:45
  • 3
    If you have alot of parameters, consider putting them info a class and pass that instead. – fredrik Aug 08 '20 at 10:45
  • Consider using object initializers instead of constructor parameters. – Eelke Aug 08 '20 at 10:47
  • @fredrik You do realize that putting parameters into a class for avoiding passing parameters into a constructor ends up being pointless, right? You still have to instantiate the class you pass onto this one – Camilo Terevinto Aug 08 '20 at 10:55
  • @CamiloTerevinto That is a matter of opinion and the use case. If there is logic surrounding those parameters, it probably far from useless since that logic can be moved and tested seperatly as well. With the amount of, or lack of, information in the post - we simply don't know if it would be pointless or not. – fredrik Aug 08 '20 at 11:00
  • Perhaps this gives you some ideas? https://stackoverflow.com/questions/6239373/how-to-avoid-too-many-parameters-problem-in-api-design – Camilo Terevinto Aug 08 '20 at 11:00
  • If [records make it into the final version of C# 9](https://daveabrock.com/2020/07/06/c-sharp-9-deep-dive-records), there will be. – Jeroen Mostert Aug 08 '20 at 13:06

0 Answers0