Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying The C# Workshop
  • Table Of Contents Toc
The C# Workshop

The C# Workshop

By : Jason Hales, Almantas Karpavicius, Mateus Viegas
4.5 (14)
close
close
The C# Workshop

The C# Workshop

4.5 (14)
By: Jason Hales, Almantas Karpavicius, Mateus Viegas

Overview of this book

C# is a powerful, versatile language that can unlock a variety of career paths. But, as with any programming language, learning C# can be a challenging process. With a wide range of different resources available, it’s difficult to know where to start. That's where The C# Workshop comes in. Written and reviewed by industry experts, it provides a fast-paced, supportive learning experience that will quickly get you writing C# code and building applications. Unlike other software development books that focus on dry, technical explanations of the underlying theory, this Workshop cuts through the noise and uses engaging examples to help you understand how each concept is applied in the real world. As you work through the book, you'll tackle realistic exercises that simulate the type of problems that software developers work on every day. These mini-projects include building a random-number guessing game, using the publisher-subscriber model to design a web file downloader, creating a to-do list using Razor Pages, generating images from the Fibonacci sequence using async/await tasks, and developing a temperature unit conversion app which you will then deploy to a production server. By the end of this book, you'll have the knowledge, skills, and confidence to advance your career and tackle your own ambitious projects with C#.
Table of Contents (10 chapters)
close
close

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.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
The C# Workshop
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon