Chapter 2. C# Language Basics

In this chapter, we introduce the basics of the C# language.

Note

Almost all of the code listings in this book are available as interactive samples in LINQPad. Working through these samples in conjunction with the book accelerates learning in that you can edit the samples and instantly see the results without needing to set up projects and solutions in Visual Studio.

To download the samples, in LINQPad, click the Samples tab, and then click “Download more samples.” LINQPad is free—go to http://www.linqpad.net.

A First C# Program

Following is a program that multiplies 12 by 30 and prints the result, 360, to the screen. The double forward slash indicates that the remainder of a line is a comment:

int x = 12 * 30;                  // Statement 1
System.Console.WriteLine (x);     // Statement 2

Our program consists of two statements. Statements in C# execute sequentially and are terminated by a semicolon. The first statement computes the expression 12 * 30 and stores the result in a variable, named x, whose type is a 32-bit integer (int). The second statement calls the WriteLine method on a class called Console, which is defined in a namespace called System. This prints the variable x to a text window on the screen.

A method performs a function; a class groups function members and data members to form an object-oriented building block. The Console class groups members that handle command-line input/output (I/O) functionality, such as the WriteLine method. A class is a kind ...

Get C# 12 in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.