Constructors
In C#, constructors are functions used to create new objects. You can also use them to set the initial values of an object. Like any function, a constructor has a name, takes arguments, and can be overloaded. A class must have at least one constructor, but if needed, it can have multiple constructors with different arguments. Even if you do not explicitly define a single constructor, a class will still have a default constructor–one that does not take any arguments or perform any actions but simply assigns memory to the newly created object and its fields.
Consider the following snippet, where a constructor for the Dog
class is being declared:
// Within a class named Dog public class Dog { // Constructor public Dog() { Console.WriteLine("A Dog object has been created"); } }
Note
You can find the code used for this example at https://packt.link/H2lUF. You can find the usage of the code at https://packt.link/4WoSX.
If a method has the same name as the class and does not provide a return
type, it is a constructor. Here, the snippet of the code is within a class named Dog
. So, the constructor is within the specified line of code. Note that by defining this constructor explicitly, you hide the default constructor. If there is one or more such custom constructors, you will no longer be able to use a default constructor. Once the new constructor is called, you should see this message printed in the console: "A Dog object has been created"
.
Fields and Class Members
You already know what a variable is: it has a type, a name, and a value, as you saw in Chapter 1, Hello C#. Variables can also exist in the class scope, and such a variable is called a field. Declaring a field is as simple as declaring a local variable. The only difference is the addition of a keyword at the start, which is the access modifier. For example, you can declare a field within the Dog
class with the public access modifier, as follows:
public string Name = "unnamed";
This line of code states that the Name
field, which is a string with the value "unnamed"
, can be accessed publicly. Besides public
, the other two main access modifiers in C# are private
and protected
, which you will look at them in detail later.
Note
You can find more information regarding access modifiers at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/access-modifiers.
Everything a class holds is called a class member. Class members can be accessed from outside of a class; however, such access needs to be granted explicitly using the public
access modifier. By default, all members have a private
access modifier.
You can access class members by writing the object name followed by a dot (.
) and the member name. For example, consider the following snippet in which two objects of the Dog
class are being created:
Dog sparky = new Dog(); Dog ricky = new Dog();
Here, you can declare two independent variables, sparky
and ricky
. However, you haven't explicitly assigned these names to the objects; note that these are only the variable names. To assign the names to the objects, you can write the following code using dot notation:
sparky.Name = "Sparky"; ricky.Name = "Ricky";
You can now have hands-on experience of creating classes and objects through an exercise.
Exercise 2.01: Creating Classes and Objects
Consider that there are two books, both by an author named New Writer
. The first one, called First Book
, was published by Publisher 1
. There is no description available for this book. Similarly, the second one is named Second Book
and was published by Publisher 2
. It has a description that simply says, "Interesting read"
.
In this exercise, you will model these books in code. The following steps will help you complete this exercise.
- Create a class called
Book
. Add fields forTitle
,Author
,Publisher
,Description
, and the number of pages. You must print this information from outside the class, so make sure every field ispublic
:public class Book { public string Title; public string Author; public string Publisher; public int Pages; public string Description; }
- Create a class named
Solution
, with theMain
method. As you saw in Chapter 1, Hello C#, this class with theMain
method is the starting point of your application:public static class Solution { public static void Main() { } }
- Inside the
Main
method, create an object for the first book and set the values for the fields, as follows:Book book1 = new Book(); book1.Author = "New Writer"; book1.Title = "First Book"; book1.Publisher = "Publisher 1";
Here, a new object named book1
is created. Values are assigned to different fields by writing dot (.
) followed by the field name. The first book does not have a description, so you can omit the field book1.Description
.
- Repeat this step for the second book. For this book, you need to set a value for the
Description
field as well:Book book2 = new Book(); book2.Author = "New Writer"; book2.Title = "Second Book"; book2.Publisher = "Publisher 2"; book2.Description = "Interesting read";
In practice, you will rarely see fields with public access modifiers. Data mutates easily, and you might not want to leave your program open to external changes after initialization.
- Inside the
Solution
class, create a method namedPrint
, which takes aBook
object as an argument and prints all fields and their values. Use string interpolation to concatenate book information and print it to the console usingConsole.WriteLine()
, as follows:private static void Print(Book book) { Console.WriteLine($"Author: {book.Author}, " + $"Title: {book.Title}, " + $"Publisher: {book.Publisher}, " + $"Description: {book.Description}."); }
- Inside the
Main
method, call thePrint
method forbook1
andbook2
:Print(book1); Print(book2);
Upon running this code, you will see the following output on the console:
Author: New Writer, Title: First Book, Publisher: Publisher 1, Description: . Author: New Writer, Title: Second Book, Publisher: Publisher 2, Description: Interesting read.
Note
You can find the code used for this exercise at https://packt.link/MGT9b.
In this exercise, you saw how to use fields and class members are used in simple programs. Now proceed to know about reference types.