How to store all ctor parameters in fieldsHow do I calculate someone's age in C#?Hidden Features of C#?How do...

How do I add a strong "onion flavor" to the biryani (in restaurant style)?

In the Lost in Space intro why was Dr. Smith actor listed as a special guest star?

Integral problem. Unsure of the approach.

How can I differentiate duration vs starting time

How can changes in personality/values of a person who turned into a vampire be explained?

Identical projects by students at two different colleges: still plagiarism?

Can I do anything else with aspersions other than cast them?

How Create a list of the first 10,000 digits of Pi and sum it?

Why does this quiz question say that protons and electrons do not combine to form neutrons?

Why write a book when there's a movie in my head?

Why would you use 2 alternate layout buttons instead of 1, when only one can be selected at once

How bad is a Computer Science course that doesn't teach Design Patterns?

Sets which are both Sum-free and Product-free.

How do I write a maintainable, fast, compile-time bit-mask in C++?

Including proofs of known theorems in master's thesis

Buying a "Used" Router

Can you wish for more wishes from an Efreeti bound to service via an Efreeti Bottle?

Do the speed limit reductions due to pollution also apply to electric cars in France?

What does "don't have a baby" imply or mean in this sentence?

Is it common to refer to someone as "Prof. Dr. [LastName]"?

Build ASCII Podiums

How does holding onto an active but un-used credit card affect your ability to get a loan?

Is layered encryption more secure than long passwords?

Have the UK Conservatives lost the working majority and if so, what does this mean?



How to store all ctor parameters in fields


How do I calculate someone's age in C#?Hidden Features of C#?How do I enumerate an enum in C#?What is the difference between a field and a property?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How to loop through all enum values in C#?How do I generate a random int number in C#?What is a NullReferenceException, and how do I fix it?How to avoid “too many parameters” problem in API design?Evaluate equality among n variables, without check each pair













6















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









New contributor




Fredrik Persson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2





    As of my knowledge no! :(

    – abhinavxeon
    1 hour ago











  • 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
    1 hour ago






  • 1





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

    – Nanna
    1 hour ago






  • 1





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

    – mjwills
    1 hour ago











  • Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.

    – SeM
    1 hour ago


















6















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









New contributor




Fredrik Persson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2





    As of my knowledge no! :(

    – abhinavxeon
    1 hour ago











  • 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
    1 hour ago






  • 1





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

    – Nanna
    1 hour ago






  • 1





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

    – mjwills
    1 hour ago











  • Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.

    – SeM
    1 hour ago
















6












6








6


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









New contributor




Fredrik Persson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












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









New contributor




Fredrik Persson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Fredrik Persson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 1 hour ago









croxy

2,83061938




2,83061938






New contributor




Fredrik Persson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 1 hour ago









Fredrik PerssonFredrik Persson

342




342




New contributor




Fredrik Persson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Fredrik Persson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Fredrik Persson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 2





    As of my knowledge no! :(

    – abhinavxeon
    1 hour ago











  • 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
    1 hour ago






  • 1





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

    – Nanna
    1 hour ago






  • 1





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

    – mjwills
    1 hour ago











  • Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.

    – SeM
    1 hour ago
















  • 2





    As of my knowledge no! :(

    – abhinavxeon
    1 hour ago











  • 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
    1 hour ago






  • 1





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

    – Nanna
    1 hour ago






  • 1





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

    – mjwills
    1 hour ago











  • Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.

    – SeM
    1 hour ago










2




2





As of my knowledge no! :(

– abhinavxeon
1 hour ago





As of my knowledge no! :(

– abhinavxeon
1 hour ago













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
1 hour ago





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
1 hour ago




1




1





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

– Nanna
1 hour ago





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

– Nanna
1 hour ago




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
1 hour ago





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

– mjwills
1 hour ago













Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.

– SeM
1 hour ago







Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.

– SeM
1 hour ago














5 Answers
5






active

oldest

votes


















4














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































    2














    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































      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





















      • 5





        Per .NET coding convention, properties have first letter upper-case

        – Teejay
        1 hour ago






      • 5





        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
        1 hour ago








      • 1





        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
        1 hour ago



















      1














      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








      New contributor




      Shawn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




























        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

























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


          }
          });






          Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.










          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

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          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




























            4














            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


























              4












              4








              4







              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 1 hour ago









              Jonas HøghJonas Høgh

              7,25311737




              7,25311737

























                  2














                  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




























                    2














                    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


























                      2












                      2








                      2







                      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 1 hour ago









                      ThisIsMeThisIsMe

                      211




                      211























                          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





















                          • 5





                            Per .NET coding convention, properties have first letter upper-case

                            – Teejay
                            1 hour ago






                          • 5





                            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
                            1 hour ago








                          • 1





                            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
                            1 hour ago
















                          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





















                          • 5





                            Per .NET coding convention, properties have first letter upper-case

                            – Teejay
                            1 hour ago






                          • 5





                            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
                            1 hour ago








                          • 1





                            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
                            1 hour ago














                          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 1 hour ago

























                          answered 1 hour ago









                          NeilNeil

                          4,84211537




                          4,84211537








                          • 5





                            Per .NET coding convention, properties have first letter upper-case

                            – Teejay
                            1 hour ago






                          • 5





                            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
                            1 hour ago








                          • 1





                            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
                            1 hour ago














                          • 5





                            Per .NET coding convention, properties have first letter upper-case

                            – Teejay
                            1 hour ago






                          • 5





                            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
                            1 hour ago








                          • 1





                            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
                            1 hour ago








                          5




                          5





                          Per .NET coding convention, properties have first letter upper-case

                          – Teejay
                          1 hour ago





                          Per .NET coding convention, properties have first letter upper-case

                          – Teejay
                          1 hour ago




                          5




                          5





                          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
                          1 hour ago







                          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
                          1 hour ago






                          1




                          1





                          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
                          1 hour ago





                          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
                          1 hour ago











                          1














                          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








                          New contributor




                          Shawn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.

























                            1














                            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








                            New contributor




                            Shawn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.























                              1












                              1








                              1







                              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








                              New contributor




                              Shawn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.










                              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








                              New contributor




                              Shawn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.









                              share|improve this answer



                              share|improve this answer






                              New contributor




                              Shawn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.









                              answered 59 mins ago









                              ShawnShawn

                              313




                              313




                              New contributor




                              Shawn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.





                              New contributor





                              Shawn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.






                              Shawn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.























                                  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 43 mins ago

























                                      answered 1 hour ago









                                      Alex LeoAlex Leo

                                      7651213




                                      7651213






















                                          Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.










                                          draft saved

                                          draft discarded


















                                          Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.













                                          Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.












                                          Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.
















                                          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

                                          Szabolcs (Ungheria) Altri progetti | Menu di navigazione48°10′14.56″N 21°29′33.14″E /...

                                          Discografia di Klaus Schulze Indice Album in studio | Album dal vivo | Singoli | Antologie | Colonne...

                                          How to make inet_server_addr() return localhost in spite of ::1/128RETURN NEXT in Postgres FunctionConnect to...