Chapter 2. Speaking C#

This chapter is about the C# language---the grammar and vocabulary that you will use every day to write the source code for your applications.

Programming languages have many similarities to human languages, except that in programming languages, we can make up our own words, just like Dr. Seuss!

In a book written by Dr. Seuss in 1950, If I Ran the Zoo states that:

"And then, just to show them, I'll sail to Ka-Troo And Bring Back an It-Kutch a Preep and a Proo A Nerkle, a Nerd and a Seersucker, too!"

To learn to speak C#, you will need to create some simple applications. To avoid overloading you with too much information too soon, the first few chapters of this book will use the simplest type of application: a console application.

This chapter covers the following topics:

  • Understanding C# basics
  • Declaring variables
  • Building console applications
  • Operating on variables

Understanding C# basics

Let's start with looking at the basics of the grammar and vocabulary of C#. In this chapter, you will create multiple console applications, each showing a feature of the C# language.

To manage these projects with Visual Studio 2017, we will put them all in a single solution. Visual Studio 2017 can only have one solution open at any one time, but each solution can group together multiple projects. A project can build a console application, a Windows desktop application, a web application, and dozens of others.

To manage these projects with Visual Studio Code, which does not support solutions, we will manually create a container folder named Chapter02. If you would like to use Visual Studio Code, skip to the section titled Using Visual Studio Code on macOS, Linux, or Windows.

Using Visual Studio 2017

Start Microsoft Visual Studio 2017. In Visual Studio, press Ctrl + Shift + N or choose the File | New | Project... menu.

In the New Project dialog, in the Installed | Templates list, expand Other Project Types and select Visual Studio Solutions. In the list at the center, select Blank Solution, type the name Chapter02, change the location to C:Code, and then click on OK, as shown in the following screenshot:

Using Visual Studio 2017

If you were to run File Explorer, you would see that Visual Studio has created a folder named Chapter02 with a Visual Studio solution named Chapter02 inside it, as shown in the following screenshot:

Using Visual Studio 2017

In Visual Studio, navigate to File | Add | New Project..., as shown in the following screenshot. This will add a new project to the blank solution:

Using Visual Studio 2017

In the Add New Project dialog, in the Installed | Templates list, expand Visual C#, and select .NET Core. In the list at the center, select Console App (.NET Core), type the name Ch02_Basics, ensure that .NET Framework 4.6.2 (or later) is selected at the top, and then click on OK, as shown in the following screenshot:

Using Visual Studio 2017

If you were to run File Explorer, you would see that Visual Studio has created a new folder with some files and subfolders inside it. You don't need to know what all these do yet. The code you will write will be stored in the file named Program.cs, as shown in the following screenshot:

Using Visual Studio 2017

In Visual Studio, the Solution Explorer window shows the same files as the ones in the preceding screenshot of the file system.

Some folders and files, for example, the bin folder, are hidden by default in Solution Explorer. At the top of the window is a toolbar button named Show All Files. Toggle this button to show and hide folders and files, as shown in the following screenshot:

Using Visual Studio 2017

Using Visual Studio Code on macOS, Linux, or Windows

If you completed Chapter 1, Hello, C#! Welcome, .NET Core!, then you will already have a Code folder in your user folder. If not, create it, and then create a subfolder named Chapter02, and then a sub-subfolder named Ch02_Basics, as shown in the following screenshot:

Using Visual Studio Code on macOS, Linux, or Windows

Start Visual Studio Code and open the /Chapter02/Ch02_Basics/ folder.

In Visual Studio Code, navigate to View | Integrated Terminal, and enter the following command:

dotnet new console

In the Explorer, click the Program.cs file, and then click Yes and Restore to restore dependencies, as shown in the following screenshot:

Using Visual Studio Code on macOS, Linux, or Windows

C# grammar

The grammar of C# includes statements and blocks.

Statements

In English, we indicate the end of a sentence with a full stop. A sentence can be composed of multiple words and phrases. The order of words is part of grammar. For example, in English, we say: the black cat. The adjective, black, comes before the noun, cat. French grammar has a different order; the adjective comes after the noun, "le chat noir". The order matters.

C# indicates the end of a statement with a semicolon. A statement can be composed of multiple variables and expressions.

In the following statement, FullName is a variable and FirstName + LastName is an expression:

    var FullName = FirstName + LastName; 

The expression is made up of an operand (FirstName), an operator (+), and another operand (LastName). The order matters.

Comments

You can add comments to explain your code using a double slash //.

The compiler ignores everything after the // until the end of the line; for example:

    var TotalPrice = Cost + Tax; // Tax is 20% of the Cost 

Note

Visual Studio 2017 and Visual Studio Code will add or remove the comment (double slashes) at the start of the currently selected line(s) if you press Ctrl + K + C or Ctrl + K + U. In macOS, press Cmd instead of Ctrl.

To write a multiline comment, use /* at the beginning and */ at the end of the comment, as shown in the following code:

    /* 
    This is a multi-line  
    comment. 
    */ 

Blocks

In English, we indicate a paragraph by starting a new line. C# indicates a block of code with curly brackets { }. Blocks start with a declaration to indicate what it is defining. For example, a block can define a namespace, a class, a method, or a statement. You will learn what these are later.

In your current project, note the grammar of C# written for you by the Visual Studio template or by the dotnet CLI tool.

In the following example, I have added some comments to describe the code:

    using System; // a semicolon indicates the end of a statement 
 
    class Program 
    { 
      static void Main(string[] args) 
      { // the start of a block 
        Console.WriteLine("Hello World!"); // a statement 
      } // the end of a block 
    } 

C# vocabulary

Some of the 79 predefined, reserved keywords that you will see in this chapter include using, namespace, class, static, int, string, double, bool, var, if, switch, break, while, do, for, and foreach.

Visual Studio 2017 shows C# keywords in blue to make them easier to spot. In the following screenshot, using, namespace, class, static, void, and string are part of the vocabulary of C#:

C# vocabulary

The equivalent for Visual Studio Code is shown in the following screenshot:

C# vocabulary

Note

Both Visual Studio 2017 and Visual Studio Code allow you to customize the color scheme. In Visual Studio 2017, navigate to Tools | Options | Environment | Fonts and Colors. In Visual Studio Code, navigate to Code | Preferences | Color Theme.

C# keywords

There are another 25 contextual keywords that only have a special meaning in a specific context. However, that still means there are only 104 actual C# keywords in the language.

English has more than 250,000 distinct words. How does C# get away with only having 104 keywords? Why is C# so difficult to learn if it has so few words?

One of the key differences between a human language and a programming language is that developers need to be able to define new "words" with new meanings.

Apart from the 104 keywords in the C# language, this book will teach you about some of the hundreds of thousands of "words" that other developers have defined. You will also learn how to define your own "words".

Note

Programmers all over the world must learn English because most programming languages use English words like namespace and class. There are programming languages that use other human languages, such as Arabic, but they are rare. This YouTube video shows a demonstration of an Arabic programming language: https://www.youtube.com/watch?v=77KAHPZUR8g

Writing the code

Plain text editors such as Notepad don't help you write correct English, as shown in the following screenshot:

Writing the code

Notepad won't help you write correct C# either:

Writing the code

Microsoft Word helps you write English by highlighting spelling mistakes with red squiggles (it should be ice-cream) and grammatical errors with blue squiggles (sentences should have an uppercase first letter).

Writing the code

Similarly, Visual Studio 2017 and Visual Studio Code help you write C# code by highlighting spelling mistakes (the method name should be WriteLine with an uppercase L) and grammatical errors (statements must end with a semicolon).

Visual Studio 2017 constantly watches what you type and gives you feedback by highlighting problems with colored squiggly lines under your code and showing the Error List window (known as the Problems window in Visual Studio Code), as you can see in the following screenshot:

Writing the code

Note

You can ask Visual Studio 2017 to do a complete check of your code by choosing Build | Build  Solution or pressing F6 .

Visual Studio Code has a similar Problems window, as shown in the following screenshot:

Writing the code

Verbs are methods

In English, verbs are doing or action words. In C#, doing or action words are called methods. There are literally hundreds of thousands of methods available to C#.

In English, verbs change how they are written based on when in time the action happens. For example, Amir was jumping in the past, Beth jumps in the present, they jumped in the past, and Charlie will jump in the future.

In C#, methods such as WriteLine change how they are called or executed based on the specifics of the action. This is called overloading, which we will cover in more detail in Chapter 6, Building Your Own Types with Object-Oriented Programming. Consider the following example:

    // outputs a carriage-return 
    Console.WriteLine();  
    // outputs the greeting and a carriage-return 
    Console.WriteLine("Hello Ahmed");  
    // outputs a formatted number and date 
    Console.WriteLine("Temperature on {0:D} is {1}°C.", 
      DateTime.Today, 23.4); 

A different analogy is that some words are spelled the same but have different meanings depending on the context.

Nouns are types, fields, and variables

In English, nouns are names that refer to things. For example, Fido is the name of a dog. The word "dog" tells us the type of thing that Fido is. To order Fido to fetch a ball, we would use his name.

In C#, their equivalents are types, fields, and variables. There are tens of thousands of types available to C#. Note that I don't say, "There are tens of thousands of types in C#."

The difference is subtle but important. C# (the language) only has a few keywords for types, such as string and int. Strictly speaking, C# doesn't define any types. Keywords such as string that look like types are aliases. Those aliases represent types provided by the platform on which C# runs.

C# cannot exist alone. It is a language that runs on variants of .NET. In theory, someone could write a compiler for C# that uses a different platform, with different underlying types. In practice, the platform for C# is one of the .NET platforms. It is .NET that provides the tens of thousands of types to C#. Those types include System.Int32, which the C# keyword alias int maps to, as well as much more complex types, such as System.Xml.Linq.XDocument.

Note that the term type is often confused with class. Have you ever played the parlor game, Twenty Questions, also known as Animal, Vegetable, or Mineral? In the game, every thing can be categorized as an animal, vegetable, or mineral. In C#, every type can be categorized as a class, struct, enum, interface, or delegate. The C# keyword string is a class, but int is a struct. So, it is best to use the term type to include both.

Counting types and methods

Let's write some code to find out how many types and methods are available to C# in our simple console application.

Don't worry about how this code works. It uses a technique called reflection, which is beyond the scope of this book.

Start by adding the following statements at the top of the Program.cs file:

    using System.Linq; 
    using System.Reflection; 

Inside the Main method, delete the statement that writes Hello World!, and replace it with the following code:

    // loop through the assemblies that this application references 
    foreach (var r in  Assembly.GetEntryAssembly() 
      .GetReferencedAssemblies()) 
    { 
      // load the assembly so we can read its details 
      var a = Assembly.Load(new AssemblyName(r.FullName)); 
      // declare a variable to count the total number of methods 
      int methodCount = 0; 
      // loop through all the types in the assembly 
      foreach (var t in a.DefinedTypes) 
      { 
        // add up the counts of methods 
        methodCount += t.GetMethods().Count(); 
      } 
      // output the count of types and their methods 
      Console.WriteLine($"{a.DefinedTypes.Count():N0} types " + 
        $"with {methodCount:N0} methods in {r.Name} assembly."); 
    } 

Building and running with Visual Studio 2017

Press Ctrl + F5 to save, compile, and run your application without the debugger attached, or click on the Debug menu and then Start Without Debugging.

You will see the following output that shows the actual number of types and methods that are available to you in the simplest application when running on Windows:

23 types with 258 methods in System.Runtime assembly.
0 types with 0 methods in System.Reflection assembly.
87 types with 917 methods in System.Linq assembly.
38 types with 545 methods in System.Console assembly.

Building and running with Visual Studio Code

At Integrated Terminal, enter the following command:

dotnet run

You will see the following output that shows the actual number of types and methods that are available to you in the simplest application when running on macOS:

23 types with 258 methods in System.Runtime assembly.
0 types with 0 methods in System.Reflection assembly.
87 types with 917 methods in System.Linq assembly.
59 types with 721 methods in System.Console assembly.

Note

The numbers of types and methods displayed may be different depending on the platform that you are using.

Add the following statements at the top of the Main method. By declaring variables that use types in other assemblies, those assemblies are loaded with our application. This allows our code to see all the types and methods in them:

    static void Main(string[] args) 
    { 
      System.Xml.XmlReader reader;

      System.Xml.Linq.XElement element;

      System.Net.Http.HttpClient client;

Note

Visual Studio 2017 Error List and Visual Studio Code Problems will show three warnings about variables that are declared but never used. You can safely ignore this warning.

In Visual Studio 2017, press Ctrl + F5.

In Visual Studio Code, enter dotnet run in Integrated Terminal.

View your output, which should look similar to the following output:

23 types with 258 methods in System.Runtime assembly.
366 types with 3,966 methods in System.Xml.ReaderWriter assembly.
64 types with 1,121 methods in System.Xml.XDocument assembly.
223 types with 2,346 methods in System.Net.Http assembly.
0 types with 0 methods in System.Reflection assembly.
87 types with 917 methods in System.Linq assembly.
59 types with 721 methods in System.Console assembly.

Now, you have a better sense of why learning C# is a challenge. There are many types, with many methods to learn about, and methods are only one category of member that a type can have, and other programmers are constantly defining new members!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.27.251