How to store all ctor parameters in fields












15















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?










share|improve this question




















  • 3





    As of my knowledge no! :(

    – abhinavxeon
    Feb 22 at 10:18






  • 1





    No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use the this keyword for it: (i.e _var1 = var1 )

    – Zohar Peled
    Feb 22 at 10:18






  • 2





    No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…

    – Nanna
    Feb 22 at 10:21






  • 1





    Write the parameter (e.g. int var1). Select var1 and press Control .. Options will appear to write the assignment code for you.

    – mjwills
    Feb 22 at 10:21






  • 2





    Also, I don't think oop tag is a right tag here.

    – SeM
    Feb 22 at 10:29
















15















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?










share|improve this question




















  • 3





    As of my knowledge no! :(

    – abhinavxeon
    Feb 22 at 10:18






  • 1





    No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use the this keyword for it: (i.e _var1 = var1 )

    – Zohar Peled
    Feb 22 at 10:18






  • 2





    No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…

    – Nanna
    Feb 22 at 10:21






  • 1





    Write the parameter (e.g. int var1). Select var1 and press Control .. Options will appear to write the assignment code for you.

    – mjwills
    Feb 22 at 10:21






  • 2





    Also, I don't think oop tag is a right tag here.

    – SeM
    Feb 22 at 10:29














15












15








15


1






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?










share|improve this question
















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?







c# oop






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 22 at 10:23









croxy

2,92571938




2,92571938










asked Feb 22 at 10:14









Fredrik PerssonFredrik Persson

814




814








  • 3





    As of my knowledge no! :(

    – abhinavxeon
    Feb 22 at 10:18






  • 1





    No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use the this keyword for it: (i.e _var1 = var1 )

    – Zohar Peled
    Feb 22 at 10:18






  • 2





    No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…

    – Nanna
    Feb 22 at 10:21






  • 1





    Write the parameter (e.g. int var1). Select var1 and press Control .. Options will appear to write the assignment code for you.

    – mjwills
    Feb 22 at 10:21






  • 2





    Also, I don't think oop tag is a right tag here.

    – SeM
    Feb 22 at 10:29














  • 3





    As of my knowledge no! :(

    – abhinavxeon
    Feb 22 at 10:18






  • 1





    No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use the this keyword for it: (i.e _var1 = var1 )

    – Zohar Peled
    Feb 22 at 10:18






  • 2





    No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…

    – Nanna
    Feb 22 at 10:21






  • 1





    Write the parameter (e.g. int var1). Select var1 and press Control .. Options will appear to write the assignment code for you.

    – mjwills
    Feb 22 at 10:21






  • 2





    Also, I don't think oop tag is a right tag here.

    – SeM
    Feb 22 at 10:29








3




3





As of my knowledge no! :(

– abhinavxeon
Feb 22 at 10:18





As of my knowledge no! :(

– abhinavxeon
Feb 22 at 10:18




1




1





No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use the this keyword for it: (i.e _var1 = var1 )

– Zohar Peled
Feb 22 at 10:18





No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use the this keyword for it: (i.e _var1 = var1 )

– Zohar Peled
Feb 22 at 10:18




2




2





No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…

– Nanna
Feb 22 at 10:21





No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…

– Nanna
Feb 22 at 10:21




1




1





Write the parameter (e.g. int var1). Select var1 and press Control .. Options will appear to write the assignment code for you.

– mjwills
Feb 22 at 10:21





Write the parameter (e.g. int var1). Select var1 and press Control .. Options will appear to write the assignment code for you.

– mjwills
Feb 22 at 10:21




2




2





Also, I don't think oop tag is a right tag here.

– SeM
Feb 22 at 10:29





Also, I don't think oop tag is a right tag here.

– SeM
Feb 22 at 10:29












8 Answers
8






active

oldest

votes


















9














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






share|improve this answer
























  • This is a close enough soloution for me. While it doesn't seem like it's possible to reduduce the amount of code i wont have to type it out at least!

    – Fredrik Persson
    Feb 23 at 16:45





















9














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#






share|improve this answer
























  • Do you happen to know why were primary constructors removed after all?

    – Mibac
    Feb 22 at 14:20






  • 1





    I think the announcements are lost as they were posted on the now defunct Roslyn codeplex page, but I believe the feature was controversial due to differing opinions on what should be allowed inside the body of a primary constructor. Later it was decided that allowing primary constructors only on records was a better solution, as it leaves less room for ambiguity.

    – Jonas Høgh
    Feb 22 at 16:37



















3














Short: No, Long: Yes, there is a hack.



You can use a mix of reflection and storing the parameter in a temporary array to achieve that.



class TestClass
{
public string var1 { get; set; }
public string var2 { get; set; }
public string var3 { get; set; }

public TestClass(string var1, string var2, string var3) : base()
{
var param = new { var1, var2, var3 };
PropertyInfo info = this.GetType().GetProperties();

foreach (PropertyInfo infos in info) {
foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
if (infos.Name == paramInfo.Name) {
infos.SetValue(this, paramInfo.GetValue(param, null));
}
}
}

}

}



This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.



Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.






share|improve this answer
























  • Clever trick, though I think it's worth noting that Reflection is expensive from a runtime cost perspective. Personally, any time I would want this, I'm working on a class that I really don't want to pay such costs. That being said,it certainly does the job!

    – Cort Ammon
    Feb 22 at 18:19



















1














The answer to your question is no, but you could use properties to get a similar fix:



class MyClass
{
public int Var1 {get;set;}
public int Var2 {get;set;}
public int Var3 {get;set;}
public int Var4 {get;set;}
public MyClass(){

}
}

void Main()
{
var myClass = new MyClass
{
Var1 = 1,
Var2 = 2,
Var3 = 3,
};
}





share|improve this answer





















  • 6





    Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.

    – Zohar Peled
    Feb 22 at 10:21








  • 2





    I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.

    – Zack ISSOIR
    Feb 22 at 10:21



















1














In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.



However the problem here arise from the fact that both your parameters and instance variables have the same names.



The compiler is unable to differentiate between same name variables(it night complaints of circular reference).



The use of this keyword allow us we tell the compiler that we are referring to the current instance of that variable.



I think that you can improve the code and coding per se with a better Naming approch for your variables.



Eg var1 var2 var3 they don't really say anything and make the code hard to understand.



Try to be specific and verbose :
Eg firstName, lastName, address and so forth. They are self-explanatory.






share|improve this answer

































    0














    I can think of a no easy way of populating the fields of an object within a constructor other than assigning them directly. As others have said, there may be some workarounds using reflection, but it is not even close to the simplicity of populating the fields manually.



    Maybe one way of populating the fields of a class from the constructor without adding any actual code to the constructor would be to alter the IL after build and to add the code that you would manually add yourself. This may be an interesting approach for a library or NuGet package.



    Other than that, I don't see use-cases for populating fields of a class from the constructor, without assigning them directly. If you have only a few mandatory fields, a constructor is pretty simple to implement, so it won't be worth the effort. If you have a huge constructor with a lot of parameters, then this looks like a code smell. You can use Object Initializer which is pretty straight forward.






    share|improve this answer































      0














      No, largely because this pattern's pretty rigid. For example, what if you wanted an argument that wouldn't be set to a field; what'd be the syntax for that? Most solutions you might come up with would either be constraining or about as verbose as the current approach.



      Still, that rigidity is only a problem in the general case. If this pattern works for you, then you can define it through inheritance, which is the right tool for this job.



      So, you might define a set of generic Tuple<>-like classes that you can inherit from:



      public abstract class TupleBase<T1>
      {
      public T1 Argument1 { get; private set; }

      public TupleBase(T1 argument1)
      {
      this.Argument1 = argument1;
      }
      }

      public abstract class TupleBase<T1, T2>
      {
      public T1 Argument1 { get; private set; }
      public T2 Argument2 { get; private set; }

      public TupleBase(T1 argument1, T2 argument2)
      {
      this.Argument1 = argument1;
      this.Argument2 = argument2;
      }
      }

      public abstract class TupleBase<T1, T2, T3>
      {
      public T1 Argument1 { get; private set; }
      public T2 Argument2 { get; private set; }
      public T3 Argument3 { get; private set; }

      public TupleBase(T1 argument1, T2 argument2, T3 argument3)
      {
      this.Argument1 = argument1;
      this.Argument2 = argument2;
      this.Argument3 = argument3;
      }
      }

      // Etc..


      Then



      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;
      }
      }


      becomes



      class MyClass : TupleBase<int, int, int, int>
      {
      public MyClass(int var1, int var2, int var3, int var4)
      : base(var1, var2, var3, var4)
      {
      }
      }


      .



      Inheritance is the fundamentally correct tool for this since you want MyClass to pick up on a basic pattern, i.e. inherit it. The problem you'll have in C# is that you can only inherit from one class at-a-time, so you can't just tack on additional functionality like this in all cases.



      Alternatively, you could write



      class MyClass
      {
      int var1;
      int var2;
      int var3;
      int var4;

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


      , where .SetConstructorValues() is a generic extension method



      private static System.Collections.ConcurrentDictionary<Type, Action<object, object>> ConstructorSetterDictionary { get; private set; }

      public static void SetConstructorValues<T_SetClass>(
      this T_SetClass instanceToSetValuesFor
      , params object constructorArguments
      )
      {
      var instanceType = typeof(T_SetClass);

      Action<object, object> constructorSetterAction;
      if (!ConstructorSetterDictionary.TryGetValue(
      instanceType
      , out constructorSetterAction
      ))
      {
      throw new Exception("Populate the dictionary! Also change this Exception message; it's from a StackOverflow example and not really designed to actually be written like this.");
      }

      constructorSetterAction(
      instanceToSetValuesFor
      , constructorArguments
      );
      }


      , where ConstructorSetterDictionary is a dictionary of the setter-Action<object, object>'s for each Type, inferred according to whatever logic you like (e.g., matching constructors with parameter names to fields), populated upon program startup using reflection.



      Conceptually, getting a method like this based on an object's Type is basically how virtual methods work, where the ConstructorSetterDictionary is a virtual lookup table.



      I find this sort of meta-programming to be useful in my own work, but be warned that, at some point, it stops being C#.






      share|improve this answer

































        0














        You can use tupple "magic".



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





        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54824786%2fhow-to-store-all-ctor-parameters-in-fields%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          8 Answers
          8






          active

          oldest

          votes








          8 Answers
          8






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          9














          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






          share|improve this answer
























          • This is a close enough soloution for me. While it doesn't seem like it's possible to reduduce the amount of code i wont have to type it out at least!

            – Fredrik Persson
            Feb 23 at 16:45


















          9














          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






          share|improve this answer
























          • This is a close enough soloution for me. While it doesn't seem like it's possible to reduduce the amount of code i wont have to type it out at least!

            – Fredrik Persson
            Feb 23 at 16:45
















          9












          9








          9







          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






          share|improve this answer













          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







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Feb 22 at 10:25









          ThisIsMeThisIsMe

          1141




          1141













          • This is a close enough soloution for me. While it doesn't seem like it's possible to reduduce the amount of code i wont have to type it out at least!

            – Fredrik Persson
            Feb 23 at 16:45





















          • This is a close enough soloution for me. While it doesn't seem like it's possible to reduduce the amount of code i wont have to type it out at least!

            – Fredrik Persson
            Feb 23 at 16:45



















          This is a close enough soloution for me. While it doesn't seem like it's possible to reduduce the amount of code i wont have to type it out at least!

          – Fredrik Persson
          Feb 23 at 16:45







          This is a close enough soloution for me. While it doesn't seem like it's possible to reduduce the amount of code i wont have to type it out at least!

          – Fredrik Persson
          Feb 23 at 16:45















          9














          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#






          share|improve this answer
























          • Do you happen to know why were primary constructors removed after all?

            – Mibac
            Feb 22 at 14:20






          • 1





            I think the announcements are lost as they were posted on the now defunct Roslyn codeplex page, but I believe the feature was controversial due to differing opinions on what should be allowed inside the body of a primary constructor. Later it was decided that allowing primary constructors only on records was a better solution, as it leaves less room for ambiguity.

            – Jonas Høgh
            Feb 22 at 16:37
















          9














          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#






          share|improve this answer
























          • Do you happen to know why were primary constructors removed after all?

            – Mibac
            Feb 22 at 14:20






          • 1





            I think the announcements are lost as they were posted on the now defunct Roslyn codeplex page, but I believe the feature was controversial due to differing opinions on what should be allowed inside the body of a primary constructor. Later it was decided that allowing primary constructors only on records was a better solution, as it leaves less room for ambiguity.

            – Jonas Høgh
            Feb 22 at 16:37














          9












          9








          9







          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#






          share|improve this answer













          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#







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Feb 22 at 10:26









          Jonas HøghJonas Høgh

          7,30311737




          7,30311737













          • Do you happen to know why were primary constructors removed after all?

            – Mibac
            Feb 22 at 14:20






          • 1





            I think the announcements are lost as they were posted on the now defunct Roslyn codeplex page, but I believe the feature was controversial due to differing opinions on what should be allowed inside the body of a primary constructor. Later it was decided that allowing primary constructors only on records was a better solution, as it leaves less room for ambiguity.

            – Jonas Høgh
            Feb 22 at 16:37



















          • Do you happen to know why were primary constructors removed after all?

            – Mibac
            Feb 22 at 14:20






          • 1





            I think the announcements are lost as they were posted on the now defunct Roslyn codeplex page, but I believe the feature was controversial due to differing opinions on what should be allowed inside the body of a primary constructor. Later it was decided that allowing primary constructors only on records was a better solution, as it leaves less room for ambiguity.

            – Jonas Høgh
            Feb 22 at 16:37

















          Do you happen to know why were primary constructors removed after all?

          – Mibac
          Feb 22 at 14:20





          Do you happen to know why were primary constructors removed after all?

          – Mibac
          Feb 22 at 14:20




          1




          1





          I think the announcements are lost as they were posted on the now defunct Roslyn codeplex page, but I believe the feature was controversial due to differing opinions on what should be allowed inside the body of a primary constructor. Later it was decided that allowing primary constructors only on records was a better solution, as it leaves less room for ambiguity.

          – Jonas Høgh
          Feb 22 at 16:37





          I think the announcements are lost as they were posted on the now defunct Roslyn codeplex page, but I believe the feature was controversial due to differing opinions on what should be allowed inside the body of a primary constructor. Later it was decided that allowing primary constructors only on records was a better solution, as it leaves less room for ambiguity.

          – Jonas Høgh
          Feb 22 at 16:37











          3














          Short: No, Long: Yes, there is a hack.



          You can use a mix of reflection and storing the parameter in a temporary array to achieve that.



          class TestClass
          {
          public string var1 { get; set; }
          public string var2 { get; set; }
          public string var3 { get; set; }

          public TestClass(string var1, string var2, string var3) : base()
          {
          var param = new { var1, var2, var3 };
          PropertyInfo info = this.GetType().GetProperties();

          foreach (PropertyInfo infos in info) {
          foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
          if (infos.Name == paramInfo.Name) {
          infos.SetValue(this, paramInfo.GetValue(param, null));
          }
          }
          }

          }

          }



          This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.



          Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.






          share|improve this answer
























          • Clever trick, though I think it's worth noting that Reflection is expensive from a runtime cost perspective. Personally, any time I would want this, I'm working on a class that I really don't want to pay such costs. That being said,it certainly does the job!

            – Cort Ammon
            Feb 22 at 18:19
















          3














          Short: No, Long: Yes, there is a hack.



          You can use a mix of reflection and storing the parameter in a temporary array to achieve that.



          class TestClass
          {
          public string var1 { get; set; }
          public string var2 { get; set; }
          public string var3 { get; set; }

          public TestClass(string var1, string var2, string var3) : base()
          {
          var param = new { var1, var2, var3 };
          PropertyInfo info = this.GetType().GetProperties();

          foreach (PropertyInfo infos in info) {
          foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
          if (infos.Name == paramInfo.Name) {
          infos.SetValue(this, paramInfo.GetValue(param, null));
          }
          }
          }

          }

          }



          This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.



          Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.






          share|improve this answer
























          • Clever trick, though I think it's worth noting that Reflection is expensive from a runtime cost perspective. Personally, any time I would want this, I'm working on a class that I really don't want to pay such costs. That being said,it certainly does the job!

            – Cort Ammon
            Feb 22 at 18:19














          3












          3








          3







          Short: No, Long: Yes, there is a hack.



          You can use a mix of reflection and storing the parameter in a temporary array to achieve that.



          class TestClass
          {
          public string var1 { get; set; }
          public string var2 { get; set; }
          public string var3 { get; set; }

          public TestClass(string var1, string var2, string var3) : base()
          {
          var param = new { var1, var2, var3 };
          PropertyInfo info = this.GetType().GetProperties();

          foreach (PropertyInfo infos in info) {
          foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
          if (infos.Name == paramInfo.Name) {
          infos.SetValue(this, paramInfo.GetValue(param, null));
          }
          }
          }

          }

          }



          This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.



          Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.






          share|improve this answer













          Short: No, Long: Yes, there is a hack.



          You can use a mix of reflection and storing the parameter in a temporary array to achieve that.



          class TestClass
          {
          public string var1 { get; set; }
          public string var2 { get; set; }
          public string var3 { get; set; }

          public TestClass(string var1, string var2, string var3) : base()
          {
          var param = new { var1, var2, var3 };
          PropertyInfo info = this.GetType().GetProperties();

          foreach (PropertyInfo infos in info) {
          foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
          if (infos.Name == paramInfo.Name) {
          infos.SetValue(this, paramInfo.GetValue(param, null));
          }
          }
          }

          }

          }



          This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.



          Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Feb 22 at 10:35









          ShawnShawn

          3668




          3668













          • Clever trick, though I think it's worth noting that Reflection is expensive from a runtime cost perspective. Personally, any time I would want this, I'm working on a class that I really don't want to pay such costs. That being said,it certainly does the job!

            – Cort Ammon
            Feb 22 at 18:19



















          • Clever trick, though I think it's worth noting that Reflection is expensive from a runtime cost perspective. Personally, any time I would want this, I'm working on a class that I really don't want to pay such costs. That being said,it certainly does the job!

            – Cort Ammon
            Feb 22 at 18:19

















          Clever trick, though I think it's worth noting that Reflection is expensive from a runtime cost perspective. Personally, any time I would want this, I'm working on a class that I really don't want to pay such costs. That being said,it certainly does the job!

          – Cort Ammon
          Feb 22 at 18:19





          Clever trick, though I think it's worth noting that Reflection is expensive from a runtime cost perspective. Personally, any time I would want this, I'm working on a class that I really don't want to pay such costs. That being said,it certainly does the job!

          – Cort Ammon
          Feb 22 at 18:19











          1














          The answer to your question is no, but you could use properties to get a similar fix:



          class MyClass
          {
          public int Var1 {get;set;}
          public int Var2 {get;set;}
          public int Var3 {get;set;}
          public int Var4 {get;set;}
          public MyClass(){

          }
          }

          void Main()
          {
          var myClass = new MyClass
          {
          Var1 = 1,
          Var2 = 2,
          Var3 = 3,
          };
          }





          share|improve this answer





















          • 6





            Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.

            – Zohar Peled
            Feb 22 at 10:21








          • 2





            I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.

            – Zack ISSOIR
            Feb 22 at 10:21
















          1














          The answer to your question is no, but you could use properties to get a similar fix:



          class MyClass
          {
          public int Var1 {get;set;}
          public int Var2 {get;set;}
          public int Var3 {get;set;}
          public int Var4 {get;set;}
          public MyClass(){

          }
          }

          void Main()
          {
          var myClass = new MyClass
          {
          Var1 = 1,
          Var2 = 2,
          Var3 = 3,
          };
          }





          share|improve this answer





















          • 6





            Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.

            – Zohar Peled
            Feb 22 at 10:21








          • 2





            I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.

            – Zack ISSOIR
            Feb 22 at 10:21














          1












          1








          1







          The answer to your question is no, but you could use properties to get a similar fix:



          class MyClass
          {
          public int Var1 {get;set;}
          public int Var2 {get;set;}
          public int Var3 {get;set;}
          public int Var4 {get;set;}
          public MyClass(){

          }
          }

          void Main()
          {
          var myClass = new MyClass
          {
          Var1 = 1,
          Var2 = 2,
          Var3 = 3,
          };
          }





          share|improve this answer















          The answer to your question is no, but you could use properties to get a similar fix:



          class MyClass
          {
          public int Var1 {get;set;}
          public int Var2 {get;set;}
          public int Var3 {get;set;}
          public int Var4 {get;set;}
          public MyClass(){

          }
          }

          void Main()
          {
          var myClass = new MyClass
          {
          Var1 = 1,
          Var2 = 2,
          Var3 = 3,
          };
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Feb 22 at 10:21

























          answered Feb 22 at 10:19









          NeilNeil

          4,84211537




          4,84211537








          • 6





            Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.

            – Zohar Peled
            Feb 22 at 10:21








          • 2





            I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.

            – Zack ISSOIR
            Feb 22 at 10:21














          • 6





            Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.

            – Zohar Peled
            Feb 22 at 10:21








          • 2





            I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.

            – Zack ISSOIR
            Feb 22 at 10:21








          6




          6





          Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.

          – Zohar Peled
          Feb 22 at 10:21







          Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.

          – Zohar Peled
          Feb 22 at 10:21






          2




          2





          I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.

          – Zack ISSOIR
          Feb 22 at 10:21





          I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.

          – Zack ISSOIR
          Feb 22 at 10:21











          1














          In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.



          However the problem here arise from the fact that both your parameters and instance variables have the same names.



          The compiler is unable to differentiate between same name variables(it night complaints of circular reference).



          The use of this keyword allow us we tell the compiler that we are referring to the current instance of that variable.



          I think that you can improve the code and coding per se with a better Naming approch for your variables.



          Eg var1 var2 var3 they don't really say anything and make the code hard to understand.



          Try to be specific and verbose :
          Eg firstName, lastName, address and so forth. They are self-explanatory.






          share|improve this answer






























            1














            In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.



            However the problem here arise from the fact that both your parameters and instance variables have the same names.



            The compiler is unable to differentiate between same name variables(it night complaints of circular reference).



            The use of this keyword allow us we tell the compiler that we are referring to the current instance of that variable.



            I think that you can improve the code and coding per se with a better Naming approch for your variables.



            Eg var1 var2 var3 they don't really say anything and make the code hard to understand.



            Try to be specific and verbose :
            Eg firstName, lastName, address and so forth. They are self-explanatory.






            share|improve this answer




























              1












              1








              1







              In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.



              However the problem here arise from the fact that both your parameters and instance variables have the same names.



              The compiler is unable to differentiate between same name variables(it night complaints of circular reference).



              The use of this keyword allow us we tell the compiler that we are referring to the current instance of that variable.



              I think that you can improve the code and coding per se with a better Naming approch for your variables.



              Eg var1 var2 var3 they don't really say anything and make the code hard to understand.



              Try to be specific and verbose :
              Eg firstName, lastName, address and so forth. They are self-explanatory.






              share|improve this answer















              In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.



              However the problem here arise from the fact that both your parameters and instance variables have the same names.



              The compiler is unable to differentiate between same name variables(it night complaints of circular reference).



              The use of this keyword allow us we tell the compiler that we are referring to the current instance of that variable.



              I think that you can improve the code and coding per se with a better Naming approch for your variables.



              Eg var1 var2 var3 they don't really say anything and make the code hard to understand.



              Try to be specific and verbose :
              Eg firstName, lastName, address and so forth. They are self-explanatory.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 22 at 10:52

























              answered Feb 22 at 10:34









              Alex LeoAlex Leo

              7771213




              7771213























                  0














                  I can think of a no easy way of populating the fields of an object within a constructor other than assigning them directly. As others have said, there may be some workarounds using reflection, but it is not even close to the simplicity of populating the fields manually.



                  Maybe one way of populating the fields of a class from the constructor without adding any actual code to the constructor would be to alter the IL after build and to add the code that you would manually add yourself. This may be an interesting approach for a library or NuGet package.



                  Other than that, I don't see use-cases for populating fields of a class from the constructor, without assigning them directly. If you have only a few mandatory fields, a constructor is pretty simple to implement, so it won't be worth the effort. If you have a huge constructor with a lot of parameters, then this looks like a code smell. You can use Object Initializer which is pretty straight forward.






                  share|improve this answer




























                    0














                    I can think of a no easy way of populating the fields of an object within a constructor other than assigning them directly. As others have said, there may be some workarounds using reflection, but it is not even close to the simplicity of populating the fields manually.



                    Maybe one way of populating the fields of a class from the constructor without adding any actual code to the constructor would be to alter the IL after build and to add the code that you would manually add yourself. This may be an interesting approach for a library or NuGet package.



                    Other than that, I don't see use-cases for populating fields of a class from the constructor, without assigning them directly. If you have only a few mandatory fields, a constructor is pretty simple to implement, so it won't be worth the effort. If you have a huge constructor with a lot of parameters, then this looks like a code smell. You can use Object Initializer which is pretty straight forward.






                    share|improve this answer


























                      0












                      0








                      0







                      I can think of a no easy way of populating the fields of an object within a constructor other than assigning them directly. As others have said, there may be some workarounds using reflection, but it is not even close to the simplicity of populating the fields manually.



                      Maybe one way of populating the fields of a class from the constructor without adding any actual code to the constructor would be to alter the IL after build and to add the code that you would manually add yourself. This may be an interesting approach for a library or NuGet package.



                      Other than that, I don't see use-cases for populating fields of a class from the constructor, without assigning them directly. If you have only a few mandatory fields, a constructor is pretty simple to implement, so it won't be worth the effort. If you have a huge constructor with a lot of parameters, then this looks like a code smell. You can use Object Initializer which is pretty straight forward.






                      share|improve this answer













                      I can think of a no easy way of populating the fields of an object within a constructor other than assigning them directly. As others have said, there may be some workarounds using reflection, but it is not even close to the simplicity of populating the fields manually.



                      Maybe one way of populating the fields of a class from the constructor without adding any actual code to the constructor would be to alter the IL after build and to add the code that you would manually add yourself. This may be an interesting approach for a library or NuGet package.



                      Other than that, I don't see use-cases for populating fields of a class from the constructor, without assigning them directly. If you have only a few mandatory fields, a constructor is pretty simple to implement, so it won't be worth the effort. If you have a huge constructor with a lot of parameters, then this looks like a code smell. You can use Object Initializer which is pretty straight forward.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Feb 22 at 12:55









                      meJustAndrewmeJustAndrew

                      2,78432248




                      2,78432248























                          0














                          No, largely because this pattern's pretty rigid. For example, what if you wanted an argument that wouldn't be set to a field; what'd be the syntax for that? Most solutions you might come up with would either be constraining or about as verbose as the current approach.



                          Still, that rigidity is only a problem in the general case. If this pattern works for you, then you can define it through inheritance, which is the right tool for this job.



                          So, you might define a set of generic Tuple<>-like classes that you can inherit from:



                          public abstract class TupleBase<T1>
                          {
                          public T1 Argument1 { get; private set; }

                          public TupleBase(T1 argument1)
                          {
                          this.Argument1 = argument1;
                          }
                          }

                          public abstract class TupleBase<T1, T2>
                          {
                          public T1 Argument1 { get; private set; }
                          public T2 Argument2 { get; private set; }

                          public TupleBase(T1 argument1, T2 argument2)
                          {
                          this.Argument1 = argument1;
                          this.Argument2 = argument2;
                          }
                          }

                          public abstract class TupleBase<T1, T2, T3>
                          {
                          public T1 Argument1 { get; private set; }
                          public T2 Argument2 { get; private set; }
                          public T3 Argument3 { get; private set; }

                          public TupleBase(T1 argument1, T2 argument2, T3 argument3)
                          {
                          this.Argument1 = argument1;
                          this.Argument2 = argument2;
                          this.Argument3 = argument3;
                          }
                          }

                          // Etc..


                          Then



                          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;
                          }
                          }


                          becomes



                          class MyClass : TupleBase<int, int, int, int>
                          {
                          public MyClass(int var1, int var2, int var3, int var4)
                          : base(var1, var2, var3, var4)
                          {
                          }
                          }


                          .



                          Inheritance is the fundamentally correct tool for this since you want MyClass to pick up on a basic pattern, i.e. inherit it. The problem you'll have in C# is that you can only inherit from one class at-a-time, so you can't just tack on additional functionality like this in all cases.



                          Alternatively, you could write



                          class MyClass
                          {
                          int var1;
                          int var2;
                          int var3;
                          int var4;

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


                          , where .SetConstructorValues() is a generic extension method



                          private static System.Collections.ConcurrentDictionary<Type, Action<object, object>> ConstructorSetterDictionary { get; private set; }

                          public static void SetConstructorValues<T_SetClass>(
                          this T_SetClass instanceToSetValuesFor
                          , params object constructorArguments
                          )
                          {
                          var instanceType = typeof(T_SetClass);

                          Action<object, object> constructorSetterAction;
                          if (!ConstructorSetterDictionary.TryGetValue(
                          instanceType
                          , out constructorSetterAction
                          ))
                          {
                          throw new Exception("Populate the dictionary! Also change this Exception message; it's from a StackOverflow example and not really designed to actually be written like this.");
                          }

                          constructorSetterAction(
                          instanceToSetValuesFor
                          , constructorArguments
                          );
                          }


                          , where ConstructorSetterDictionary is a dictionary of the setter-Action<object, object>'s for each Type, inferred according to whatever logic you like (e.g., matching constructors with parameter names to fields), populated upon program startup using reflection.



                          Conceptually, getting a method like this based on an object's Type is basically how virtual methods work, where the ConstructorSetterDictionary is a virtual lookup table.



                          I find this sort of meta-programming to be useful in my own work, but be warned that, at some point, it stops being C#.






                          share|improve this answer






























                            0














                            No, largely because this pattern's pretty rigid. For example, what if you wanted an argument that wouldn't be set to a field; what'd be the syntax for that? Most solutions you might come up with would either be constraining or about as verbose as the current approach.



                            Still, that rigidity is only a problem in the general case. If this pattern works for you, then you can define it through inheritance, which is the right tool for this job.



                            So, you might define a set of generic Tuple<>-like classes that you can inherit from:



                            public abstract class TupleBase<T1>
                            {
                            public T1 Argument1 { get; private set; }

                            public TupleBase(T1 argument1)
                            {
                            this.Argument1 = argument1;
                            }
                            }

                            public abstract class TupleBase<T1, T2>
                            {
                            public T1 Argument1 { get; private set; }
                            public T2 Argument2 { get; private set; }

                            public TupleBase(T1 argument1, T2 argument2)
                            {
                            this.Argument1 = argument1;
                            this.Argument2 = argument2;
                            }
                            }

                            public abstract class TupleBase<T1, T2, T3>
                            {
                            public T1 Argument1 { get; private set; }
                            public T2 Argument2 { get; private set; }
                            public T3 Argument3 { get; private set; }

                            public TupleBase(T1 argument1, T2 argument2, T3 argument3)
                            {
                            this.Argument1 = argument1;
                            this.Argument2 = argument2;
                            this.Argument3 = argument3;
                            }
                            }

                            // Etc..


                            Then



                            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;
                            }
                            }


                            becomes



                            class MyClass : TupleBase<int, int, int, int>
                            {
                            public MyClass(int var1, int var2, int var3, int var4)
                            : base(var1, var2, var3, var4)
                            {
                            }
                            }


                            .



                            Inheritance is the fundamentally correct tool for this since you want MyClass to pick up on a basic pattern, i.e. inherit it. The problem you'll have in C# is that you can only inherit from one class at-a-time, so you can't just tack on additional functionality like this in all cases.



                            Alternatively, you could write



                            class MyClass
                            {
                            int var1;
                            int var2;
                            int var3;
                            int var4;

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


                            , where .SetConstructorValues() is a generic extension method



                            private static System.Collections.ConcurrentDictionary<Type, Action<object, object>> ConstructorSetterDictionary { get; private set; }

                            public static void SetConstructorValues<T_SetClass>(
                            this T_SetClass instanceToSetValuesFor
                            , params object constructorArguments
                            )
                            {
                            var instanceType = typeof(T_SetClass);

                            Action<object, object> constructorSetterAction;
                            if (!ConstructorSetterDictionary.TryGetValue(
                            instanceType
                            , out constructorSetterAction
                            ))
                            {
                            throw new Exception("Populate the dictionary! Also change this Exception message; it's from a StackOverflow example and not really designed to actually be written like this.");
                            }

                            constructorSetterAction(
                            instanceToSetValuesFor
                            , constructorArguments
                            );
                            }


                            , where ConstructorSetterDictionary is a dictionary of the setter-Action<object, object>'s for each Type, inferred according to whatever logic you like (e.g., matching constructors with parameter names to fields), populated upon program startup using reflection.



                            Conceptually, getting a method like this based on an object's Type is basically how virtual methods work, where the ConstructorSetterDictionary is a virtual lookup table.



                            I find this sort of meta-programming to be useful in my own work, but be warned that, at some point, it stops being C#.






                            share|improve this answer




























                              0












                              0








                              0







                              No, largely because this pattern's pretty rigid. For example, what if you wanted an argument that wouldn't be set to a field; what'd be the syntax for that? Most solutions you might come up with would either be constraining or about as verbose as the current approach.



                              Still, that rigidity is only a problem in the general case. If this pattern works for you, then you can define it through inheritance, which is the right tool for this job.



                              So, you might define a set of generic Tuple<>-like classes that you can inherit from:



                              public abstract class TupleBase<T1>
                              {
                              public T1 Argument1 { get; private set; }

                              public TupleBase(T1 argument1)
                              {
                              this.Argument1 = argument1;
                              }
                              }

                              public abstract class TupleBase<T1, T2>
                              {
                              public T1 Argument1 { get; private set; }
                              public T2 Argument2 { get; private set; }

                              public TupleBase(T1 argument1, T2 argument2)
                              {
                              this.Argument1 = argument1;
                              this.Argument2 = argument2;
                              }
                              }

                              public abstract class TupleBase<T1, T2, T3>
                              {
                              public T1 Argument1 { get; private set; }
                              public T2 Argument2 { get; private set; }
                              public T3 Argument3 { get; private set; }

                              public TupleBase(T1 argument1, T2 argument2, T3 argument3)
                              {
                              this.Argument1 = argument1;
                              this.Argument2 = argument2;
                              this.Argument3 = argument3;
                              }
                              }

                              // Etc..


                              Then



                              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;
                              }
                              }


                              becomes



                              class MyClass : TupleBase<int, int, int, int>
                              {
                              public MyClass(int var1, int var2, int var3, int var4)
                              : base(var1, var2, var3, var4)
                              {
                              }
                              }


                              .



                              Inheritance is the fundamentally correct tool for this since you want MyClass to pick up on a basic pattern, i.e. inherit it. The problem you'll have in C# is that you can only inherit from one class at-a-time, so you can't just tack on additional functionality like this in all cases.



                              Alternatively, you could write



                              class MyClass
                              {
                              int var1;
                              int var2;
                              int var3;
                              int var4;

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


                              , where .SetConstructorValues() is a generic extension method



                              private static System.Collections.ConcurrentDictionary<Type, Action<object, object>> ConstructorSetterDictionary { get; private set; }

                              public static void SetConstructorValues<T_SetClass>(
                              this T_SetClass instanceToSetValuesFor
                              , params object constructorArguments
                              )
                              {
                              var instanceType = typeof(T_SetClass);

                              Action<object, object> constructorSetterAction;
                              if (!ConstructorSetterDictionary.TryGetValue(
                              instanceType
                              , out constructorSetterAction
                              ))
                              {
                              throw new Exception("Populate the dictionary! Also change this Exception message; it's from a StackOverflow example and not really designed to actually be written like this.");
                              }

                              constructorSetterAction(
                              instanceToSetValuesFor
                              , constructorArguments
                              );
                              }


                              , where ConstructorSetterDictionary is a dictionary of the setter-Action<object, object>'s for each Type, inferred according to whatever logic you like (e.g., matching constructors with parameter names to fields), populated upon program startup using reflection.



                              Conceptually, getting a method like this based on an object's Type is basically how virtual methods work, where the ConstructorSetterDictionary is a virtual lookup table.



                              I find this sort of meta-programming to be useful in my own work, but be warned that, at some point, it stops being C#.






                              share|improve this answer















                              No, largely because this pattern's pretty rigid. For example, what if you wanted an argument that wouldn't be set to a field; what'd be the syntax for that? Most solutions you might come up with would either be constraining or about as verbose as the current approach.



                              Still, that rigidity is only a problem in the general case. If this pattern works for you, then you can define it through inheritance, which is the right tool for this job.



                              So, you might define a set of generic Tuple<>-like classes that you can inherit from:



                              public abstract class TupleBase<T1>
                              {
                              public T1 Argument1 { get; private set; }

                              public TupleBase(T1 argument1)
                              {
                              this.Argument1 = argument1;
                              }
                              }

                              public abstract class TupleBase<T1, T2>
                              {
                              public T1 Argument1 { get; private set; }
                              public T2 Argument2 { get; private set; }

                              public TupleBase(T1 argument1, T2 argument2)
                              {
                              this.Argument1 = argument1;
                              this.Argument2 = argument2;
                              }
                              }

                              public abstract class TupleBase<T1, T2, T3>
                              {
                              public T1 Argument1 { get; private set; }
                              public T2 Argument2 { get; private set; }
                              public T3 Argument3 { get; private set; }

                              public TupleBase(T1 argument1, T2 argument2, T3 argument3)
                              {
                              this.Argument1 = argument1;
                              this.Argument2 = argument2;
                              this.Argument3 = argument3;
                              }
                              }

                              // Etc..


                              Then



                              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;
                              }
                              }


                              becomes



                              class MyClass : TupleBase<int, int, int, int>
                              {
                              public MyClass(int var1, int var2, int var3, int var4)
                              : base(var1, var2, var3, var4)
                              {
                              }
                              }


                              .



                              Inheritance is the fundamentally correct tool for this since you want MyClass to pick up on a basic pattern, i.e. inherit it. The problem you'll have in C# is that you can only inherit from one class at-a-time, so you can't just tack on additional functionality like this in all cases.



                              Alternatively, you could write



                              class MyClass
                              {
                              int var1;
                              int var2;
                              int var3;
                              int var4;

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


                              , where .SetConstructorValues() is a generic extension method



                              private static System.Collections.ConcurrentDictionary<Type, Action<object, object>> ConstructorSetterDictionary { get; private set; }

                              public static void SetConstructorValues<T_SetClass>(
                              this T_SetClass instanceToSetValuesFor
                              , params object constructorArguments
                              )
                              {
                              var instanceType = typeof(T_SetClass);

                              Action<object, object> constructorSetterAction;
                              if (!ConstructorSetterDictionary.TryGetValue(
                              instanceType
                              , out constructorSetterAction
                              ))
                              {
                              throw new Exception("Populate the dictionary! Also change this Exception message; it's from a StackOverflow example and not really designed to actually be written like this.");
                              }

                              constructorSetterAction(
                              instanceToSetValuesFor
                              , constructorArguments
                              );
                              }


                              , where ConstructorSetterDictionary is a dictionary of the setter-Action<object, object>'s for each Type, inferred according to whatever logic you like (e.g., matching constructors with parameter names to fields), populated upon program startup using reflection.



                              Conceptually, getting a method like this based on an object's Type is basically how virtual methods work, where the ConstructorSetterDictionary is a virtual lookup table.



                              I find this sort of meta-programming to be useful in my own work, but be warned that, at some point, it stops being C#.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Feb 22 at 17:08

























                              answered Feb 22 at 16:44









                              NatNat

                              60111327




                              60111327























                                  0














                                  You can use tupple "magic".



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





                                  share|improve this answer




























                                    0














                                    You can use tupple "magic".



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





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      You can use tupple "magic".



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





                                      share|improve this answer













                                      You can use tupple "magic".



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






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 13 hours ago









                                      Paul BeckerPaul Becker

                                      837




                                      837






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54824786%2fhow-to-store-all-ctor-parameters-in-fields%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

                                          ComboBox Display Member on multiple fields

                                          Is it possible to collect Nectar points via Trainline?