Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Create Constructor Using Fields/Properties in Visual Studio (like Eclipse does)

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).

like image 410
Awaken Avatar asked Jul 22 '10 17:07

Awaken


People also ask

Why we use parameterized constructor in C#?

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.

What is a default constructor C#?

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#

Can a class have multiple constructors 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.


2 Answers

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.

enter image description here

like image 156
Pouya Samie Avatar answered Sep 20 '22 08:09

Pouya Samie


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};
      }
   }
like image 36
this. __curious_geek Avatar answered Sep 20 '22 08:09

this. __curious_geek