3.4 Constructors

File Location

  1. Right click on your solution

  2. Go to Add > New Project and select Console App (.NET Framework)

  3. Name it Constructors

Visualization

class Student
{
//    1      2         3
    public student(string firstName, string lastName, int grade)
        {
//          4                  5
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Grade = grade;
        }
}
  1. Access Modifier

  2. Name of constructor (same name as class)

  3. Parameters for the constructor. The properties of the class are what your parameters can be

  4. Accessing the properties of your class using the keyword this

  5. We attach the properties to the parameters of the constructor so that when we instantiate new objects it will bring over the correct properties.

Discussion

A constructor is a better way to create objects within your class.

Instead of:

  • Creating a class

  • Identifying the properties

  • Instantiating a new object

  • Setting values to each object

like we did with donut example in the object module. We can do this more streamlined and with less lines of code by using constructors.

Constructors are used within your class. Say you make a student class. Within your student class you can use multiple constructors to construct or build out your class. Your constructors can take in different parameters and variables that your new objects could take in. There will be some example code after the explanation.

Now, within your student class, there will be a few constructors taking in different parameters such as one with no parameters, one with just first name, one with first name and last name, one with first name, last name, and grade, and so on.

Then, somewhere within your class, you will create properties available to your constructors.

In your Constructors project, delete Class1.cs. Add a class named Student and add the following code:

class Student
    {
        //Constructor 1
        public Student()
        {

        }
        //Constructor 2
        public Student(string firstName)
        {
            this.FirstName = firstName;
        }
        //Constructor 3
        public Student(string firstName, string lastName)
        {
            this.LastName = lastName;
            this.Grade = grade;
        }
        //Constructor 4
        public Student(string firstName, string lastName, int grade)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Grade = grade;
        }
        //Constructor 5
        public Student(string firstName, string lastName, int grade, int age)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Grade = grade;
            this.Age = age;
        }
        //Properties
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public int Grade { get; set; }
    }

We made a student class with 5 different constructors. Next we can instantiate new objects of the student class that take in the different parameters stated above.

Now we can go into the Program.cs file, instantiate these new objects, and associate values to the properties using only one line of code. Efficiency is key.

Your instantiations will look like this:

 class Program
    {
        static void Main(string[] args)
        {
            Student carrStudent = new Student("Carr");

            Student caliStudent = new Student("Carr", "O'Connor");

            Student carolineStudent = new Student("Caroline", "O'Connor", 8);

            Student chrisStudent = new Student("Chris", "Weiper", 5, 11);

            Console.WriteLine(chrisStudent.FirstName + ": " + chrisStudent.Age);
            Console.ReadLine();
        }
    }

Discussion

Here we instantiated 4 new objects from our student class using the different constructors and defined our values within the parenthesis of the instantiation. So when we instantiate a new object, it goes to the class we defined after the new statement, in this case it is student. Then it finds a constructor that fits the amount of parameters. The constructor checks to see if the properties are declared within the class somewhere, then the object defines the values of said properties by using the values stated within parenthesis of the new object.

Challenges

Bronze

  • Create a MobilePhone class for mobile devices

  • Have two properties: Make and Model

  • Create a constructor that allows these two arguments to be passed in for a new instance of a phone

  • Create a new phone object that tells what kind of phone you have, and print to the console

  • Example of what should print to the Console - "I own an iPhone 6."

Silver

  • Print a list of five friends and what phone they own

  • Example: Larissa has an iPhone 6. Ava has the iPhone 5. Kenn has the Samsung Galaxy. Etc...

Gold

  • Create a laptop class

  • Create at least 3 properties

  • Create a constructor for the class

  • Create a method for this class that executes some action.

Answers:

Next: Access Modifiers

Last updated