Locked lesson.
About this lesson
Constructors provide a simple way to create new objects within our code.
Exercise files
Download this lesson’s related exercise files.
45 - Intro To Classes Constructors.docx57.6 KB 45 - Intro To Classes Constructors SOLUTION.docx
59.1 KB
Quick reference
Intro To Classes: Constructors
Constructor methods allow us to pass things to our Class whenever an object is created.
When to use
Use this to pass parameters to your class in order to create an object with fewer lines of code.
Instructions
{
// Create Book Object
Book book1 = new Book("C# Programming", "John Elder", 309);
Console.WriteLine(book1.title);
}
class Book
{
public string title;
public string author;
public int pages;
public Book(string myTitle, string myAuthor, int myPages)
{
title = myTitle;
author = myAuthor;
pages = myPages;
}
}
Hints & tips
- Constructor Methods make creating objects easier
Lesson notes are only available for subscribers.