How to store all ctor parameters in fields












13















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.
















  • 3





    As of my knowledge no! :(

    – abhinavxeon
    15 hours ago






  • 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
    15 hours ago






  • 2





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

    – Nanna
    15 hours 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
    15 hours ago






  • 2





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

    – SeM
    15 hours ago
















13















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.
















  • 3





    As of my knowledge no! :(

    – abhinavxeon
    15 hours ago






  • 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
    15 hours ago






  • 2





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

    – Nanna
    15 hours 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
    15 hours ago






  • 2





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

    – SeM
    15 hours ago














13












13








13


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 15 hours ago









croxy

2,84061938




2,84061938






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 15 hours ago









Fredrik PerssonFredrik Persson

693




693




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.








  • 3





    As of my knowledge no! :(

    – abhinavxeon
    15 hours ago






  • 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
    15 hours ago






  • 2





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

    – Nanna
    15 hours 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
    15 hours ago






  • 2





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

    – SeM
    15 hours ago














  • 3





    As of my knowledge no! :(

    – abhinavxeon
    15 hours ago






  • 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
    15 hours ago






  • 2





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

    – Nanna
    15 hours 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
    15 hours ago






  • 2





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

    – SeM
    15 hours ago








3




3





As of my knowledge no! :(

– abhinavxeon
15 hours ago





As of my knowledge no! :(

– abhinavxeon
15 hours ago




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
15 hours 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
15 hours ago




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
15 hours ago





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

– Nanna
15 hours 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
15 hours ago





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

– mjwills
15 hours ago




2




2





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

– SeM
15 hours ago





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

– SeM
15 hours ago












7 Answers
7






active

oldest

votes


















8














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
    11 hours ago






  • 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
    9 hours ago



















7














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














    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.





















    • 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
      7 hours 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





















    • 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
      15 hours ago








    • 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
      15 hours ago



















    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

























          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

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8














          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
            11 hours ago






          • 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
            9 hours ago
















          8














          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
            11 hours ago






          • 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
            9 hours ago














          8












          8








          8







          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 15 hours ago









          Jonas HøghJonas Høgh

          7,29311737




          7,29311737













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

            – Mibac
            11 hours ago






          • 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
            9 hours ago



















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

            – Mibac
            11 hours ago






          • 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
            9 hours ago

















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

          – Mibac
          11 hours ago





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

          – Mibac
          11 hours ago




          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
          9 hours ago





          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
          9 hours ago













          7














          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




























            7














            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


























              7












              7








              7







              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 15 hours ago









              ThisIsMeThisIsMe

              711




              711























                  2














                  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.





















                  • 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
                    7 hours ago
















                  2














                  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.





















                  • 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
                    7 hours ago














                  2












                  2








                  2







                  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 15 hours ago









                  ShawnShawn

                  514




                  514




                  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.













                  • 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
                    7 hours ago



















                  • 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
                    7 hours ago

















                  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
                  7 hours ago





                  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
                  7 hours 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





















                  • 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
                    15 hours ago








                  • 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
                    15 hours 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





















                  • 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
                    15 hours ago








                  • 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
                    15 hours 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 15 hours ago

























                  answered 15 hours ago









                  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
                    15 hours ago








                  • 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
                    15 hours ago














                  • 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
                    15 hours ago








                  • 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
                    15 hours ago








                  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
                  15 hours 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
                  15 hours ago






                  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
                  15 hours 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
                  15 hours ago











                  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 14 hours ago

























                      answered 15 hours ago









                      Alex LeoAlex Leo

                      7651213




                      7651213























                          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 12 hours ago









                              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 8 hours ago

























                                      answered 8 hours ago









                                      NatNat

                                      60111327




                                      60111327






















                                          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

                                          How to label and detect the document text images

                                          Vallis Paradisi

                                          Tabula Rosettana