How to store all ctor parameters in fields

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.


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


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#

Tags:

C#

Oop