Is there any way to automatically create the constructor for a class based on the properties in the class like Eclipse does? (Without getting ReSharper). I'm using Visual Studio 2008 (C#).
If this is a duplicate, please link (I tried searching).
Is there any way to automatically create the constructor for a class based on the properties in the class like Eclipse does? (Without getting ReSharper). I'm using Visual Studio 2008 (C#).
If this is a duplicate, please link (I tried searching).
I answered the question here :
this is my answer :
In visual studio 2015 Update3, I have this feature.
just by Highlighting properties and then press ctrl + . and then Press Generate Constructor.
UPDATE For example, if you've highlighted 2 properties it will suggest you create a contractor with 2 parameters and if you've selected 3 it will suggest with 3 parameters and so on.
also works with VS2017.
you can use object initializer
instead of having created a constructor, if you're using C# 3.0.
Referring code that I found in some example.
class Program
{
public class Student
{
public string firstName;
public string lastName;
}
public class ScienceClass
{
public Student Student1, Student2, Student3;
}
static void Main(string[] args)
{
var student1 = new Student{firstName = "Bruce",
lastName = "Willis"};
var student2 = new Student{firstName = "George",
lastName = "Clooney"};
var student3 = new Student{firstName = "James",
lastName = "Cameron"};
var sClass = new ScienceClass{Student1 = student1,
Student2 = student2,
Student3 = student3};
}
}
No. There is the ctor snippet(not quite what you were looking for), or you can create your macro. Possibly check out Productivity macros for C#. And since you don't like ReSharper, you can use CodeRush.
Here's a pretty good work around:
Make an empty class
class MyClass{
}
Try to create an instance of the object and parse it the variable types you would like in the constructor
class Program{
static void Main(string[] args){
string var1 = "First variable is a string";
int var2 = "Second variable is an int";
Myclass foo = new MyClass(var1, var2);
//this line here is the important one
}
}
Visual Studio should give you a resolve prompt if you mouse over the new MyClass which will allow an automatic creation of the constructor and properties in the class with whatever variable names you offered in step 2. Result is as follows.
class MyClass{
private string var1;
private int var2;
public MyClass(string var1, int var2){
// TODO: Complete member initialization
this.var1 = var1;
this.var2 = var2;
}
}
Note: You could even skip step 1 and use resolve twice to firstly generate the class, then generate the innards.