DotNet-101-CSharpFundamentals
  • Introduction
  • Part 0: Solution Setup
    • 1.0: Solution Setup
  • Part 1: Data Types
    • 1.0: Variables
    • 1.1: Data Types
    • 1.2: Data Types Table
    • 1.3: Challenge Answers
    • 1.4: Strings
    • 1.5: String Challenges
    • 1.6: Challenge Answers
    • 1.7: Integers
    • 1.8: Type Conversion
  • Part 2: Boolean Logic And Conditionals
    • 2.0: Boolean Type
    • 2.1: Boolean Logic
    • 2.2: Boolean Challenges
    • 2.3: Challenge Answers
    • 2.4: if, else if, else
    • 2.5: Switch Statements
    • 2.6: Ternary Operators
  • Part 3: Objects, Methods, C# Fundamentals
    • 3.0 Objects
    • 3.1 Properties
      • Challenge Answers
    • 3.2 Methods
      • Challenge Answers
    • 3.3 Method-Overloading
    • 3.4 Constructors
      • Challenge Answers
    • 3.5 Access Modifiers
  • Part 4: Collections Arrays Control Flow
    • 4.0 Arrays
    • 4.1 Loops
    • 4.2 Dictionaries
    • Challenge Answers
    • 4.3 List
    • 4.3a: Challenge Answers
  • Part 5: Inheritance/More On Object Oriented Programming
    • 5.0 Inheritance
    • 5.1 Polymorphism
    • 5.2 Encapsulation
    • 5.3 Getters And Setters
    • 5.4 Exception Handling
  • Part 6: Structs
    • 6.0 Structs
  • Part 7: Enums
    • 7.0 Enums
  • Part 8: Null Coalescing Operator
    • 8.0 Null Coalescing Operator
  • Part 9: Interfaces
    • 9.0 Interfaces
    • 9.1 Rules
    • 9.2 Code With Intent
  • Part 10: More C#
    • 10.0 DateTime
    • 10.1-LINQ
    • Challenge Answers
  • Part 11: Reference and Value Types
    • 11.0 Reference & Value Types
  • Eleven Fifty Style Guide
Powered by GitBook
On this page
  • File Location
  • Visualization
  • Discussion
  • Discussion
  • Challenges
  1. Part 3: Objects, Methods, C# Fundamentals

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.

Previous3.3 Method-OverloadingNextChallenge Answers

Last updated 7 years ago

Access Modifiers

Answers:
Next: