0

I'm looking for a Best Practice to set a Object's properties to the constructors' parameters which have the same name. so basically my code looks the following:

public class Person
    {

        //Properties
        public string firstname;
        public string lastname;
        public string nickname;
        ...

        //Constructor
        public Person(string firstname, string lastname, string nickname, ...) {
            this.fistname = firstname;
            this.lastname = lastname;
            this.nickname = nickname;
            ...
        }
}

this is quite a common task which you encounter a lot. shoudln't there be a better way to deal with this? is there a "Best Practice" to achieve the same?

I was thinking of something like this:

public class Person
    {

        //Properties
        public string firstname;
        public string lastname;
        public string nickname;
        ...

        //Constructor
        public Person(string firstname, string lastname, string nickname, ...) {
            foreach (PropertyInfo prop in typeof(Person).GetProperties())
            {
                this.prop = prop.Name; //something like this possible?
            }
        }
}

the prop.Name would have to be kinda preprocessed and than used as the same-named variable. if i get more properties this will save alot of code i think .. thanks in advance!

phil

philx_x
  • 1,708
  • 16
  • 23
  • You may use object initializers in your code in these cases and no constructor at all: new Person { firstname = name }; – DrKoch Dec 18 '14 at 11:08
  • Understand what you want but the more explicit setting of the parameters makes the code more readable to me. Just thinking of the next developer that maintains the codebase. Just my 2 cents... – Phil Murray Dec 18 '14 at 11:08
  • @PhilMurray the only thing i could think of is adding a prefix to the parameters and the properties like this.mName = pName but i think coders shouldn't do this anymore nowadays. and furthermore this is only an example .. so no worries mate ;) – philx_x Dec 18 '14 at 11:13
  • 1
    This might be nice in theory, but: 1.) AFAIK there is no way to get parameter value using reflection. 2.) Do you really spend much time writing constructors compared to the actual business logic? – Dirk Dec 18 '14 at 11:32
  • [How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?](http://stackoverflow.com/questions/2976363/how-do-i-generate-a-constructor-from-class-fields-using-visual-studio-and-or-re) – CodeCaster Dec 18 '14 at 11:36

0 Answers0