Generate constructor with properties (C# only)Place your cursor on the instance. Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select Generate constructor in <QualifiedName> (with properties).
Generate a constructor Alternatively, you can press Ctrl+Shift+A , start typing the command name in the popup, and then choose it there. In the Generate popup, select Constructor. In the Generate dialog that appears, select type members that should be initialized in the new constructor.
A constructor in VB.NET is defined as a procedure that has the name New (rather than Initialize as in VB 6.0) and can accept arguments to allow clients to pass data into the instance to assist with initialization. Constructors do not return values and therefore are always declared as a Sub.
To call one constructor from another within the same class (for the same object instance), C# uses a colon followed by the this keyword, followed by the parameter list on the callee constructor's declaration. In this case, the constructor that takes all three parameters calls the constructor that takes two parameters.
In Visual Studio 2015 Update3 I have this feature.
Just by highlighting properties and then press Ctrl + . and then press Generate Constructor.
For example, if you've highlighted two properties it will suggest you to create a constructor with two parameters and if you've selected three it will suggest one with three parameters and so on.
It also works with Visual Studio 2017 and 2019.
ReSharper offers a Generate Constructor tool where you can select any field/properties that you want initialized. I use the Alt + Ins hot-key to access this.
C# added a new feature in Visual Studio 2010 called generate from usage. The intent is to generate the standard code from a usage pattern. One of the features is generating a constructor based off an initialization pattern.
The feature is accessible via the smart tag that will appear when the pattern is detected.
For example, let’s say I have the following class
class MyType {
}
And I write the following in my application
var v1 = new MyType(42);
A constructor taking an int
does not exist so a smart tag will show up and one of the options will be "Generate constructor stub". Selecting that will modify the code for MyType
to be the following.
class MyType {
private int p;
public MyType(int p) {
// TODO: Complete member initialization
this.p = p;
}
}
As of Visual Studio 2017, this looks to be a built-in feature. Hit Ctrl + . while your cursor is in the class body, and select "Generate Constructor" from the Quick Actions and Refactorings dropdown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With