Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The C# Workshop

You're reading from   The C# Workshop Kickstart your career as a software developer with C#

Arrow left icon
Product type Paperback
Published in Sep 2022
Publisher Packt
ISBN-13 9781800566491
Length 780 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (3):
Arrow left icon
Almantas Karpavicius Almantas Karpavicius
Author Profile Icon Almantas Karpavicius
Almantas Karpavicius
Jason Hales Jason Hales
Author Profile Icon Jason Hales
Jason Hales
Mateus Viegas Mateus Viegas
Author Profile Icon Mateus Viegas
Mateus Viegas
Arrow right icon
View More author details
Toc

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.

  1. Create a class called Book. Add fields for Title, Author, Publisher, Description, and the number of pages. You must print this information from outside the class, so make sure every field is public:
        public class Book
        {
            public string Title;
            public string Author;
            public string Publisher;
            public int Pages;
            public string Description;
        }
  2. Create a class named Solution, with the Main method. As you saw in Chapter 1, Hello C#, this class with the Main method is the starting point of your application:
        public static class Solution
        {
            public static void Main()
            {
            }
        }
  3. 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.

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

  1. Inside the Solution class, create a method named Print, which takes a Book object as an argument and prints all fields and their values. Use string interpolation to concatenate book information and print it to the console using Console.WriteLine(), as follows:
    private static void Print(Book book)
    {
        Console.WriteLine($"Author: {book.Author}, " +
                          $"Title: {book.Title}, " +
                          $"Publisher: {book.Publisher}, " +
                          $"Description: {book.Description}.");
    }
  2. Inside the Main method, call the Print method for book1 and book2:
    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.

You have been reading a chapter from
The C# Workshop
Published in: Sep 2022
Publisher: Packt
ISBN-13: 9781800566491
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime