Very common scenario: I have a class with multiple instance variables and a constructor that accepts multiple parameters. Can I somehow bind one to the other? Assigning all parameters to the instance variables is very verbose and is one of the situations that could be (and should be) covered by the convention-over-configuration principle. My example code looks like this:
public class myClass
{
private object param1;
private object param2;
private object param3;
private object param4;
public myClass(object param1, object param2, object param3, object param4)
{
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
}
}
Is there an easy way to get rid of this and let C# do its magic automatically?
While there are many plugins that can do this kind of thing – it’s worth noting that if you VS2010+’s native ability to generate constructors from a model call when a matching constructor does not exist, you can use a simple keyboard shortcut to do the work for you.
I.e. if I a stub class:
And then in a method somewhere I write something like this:
When such a constructor does not exist, a little helper button appears. If you click on that, or press
ALT+SHIFT+F10(by default) you get a menu, one of the options on which is to generate a stub constructor, which will then change theMyClasscode as follows: