How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?
I've gotten accustomed to many of the Java IDEs (Eclipse, NetBeans, and IntelliJ IDEA) providing you with a command to generate a default constructor for a class based on the fields in the class.
For example:
public class Example
{
public decimal MyNumber { get; set; }
public string Description { get; set; }
public int SomeInteger { get; set; }
// ↓↓↓ This is what I want generated ↓↓↓
public Example(decimal myNumber, string description, int someInteger)
{
MyNumber = myNumber;
Description = description;
SomeInteger = someInteger;
}
}
Having a constructor populate all of the fields of an object is such a common task in most OOP languages, I'm assuming that there is a some way for me to save time writing this boilerplate code in C#. I'm new to the C# world, so I'm wondering if I'm missing something fundamental about the language? Is there some option in Visual Studio that is obvious?
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.