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).
Parameterized Constructor in C# A constructor with at least one parameter is called a parameterized constructor. The advantage of a parameterized constructor is that you can initialize each instance of the class with a different value.
A constructor with no parameters is called a default constructor. A default constructor has every instance of the class to be initialized to the same values. The default constructor initializes all numeric fields to zero and all string and object fields to null inside a class. Example : C#
A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.
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};
}
}
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