Chapter 2. Basic Coding in C#

All programming languages have to provide certain capabilities. It must be possible to express the calculations and operations that our code should perform. Programs need to be able to make decisions based on their input. Sometimes we will need to perform tasks repeatedly. These fundamental features are the very stuff of programming, and this chapter will show how these things work in C#.

Depending on your background, some of this chapter’s content may seem very familiar. C# is said to be from the “C family” of languages. C is a hugely influential programming language, and numerous languages have borrowed much of its syntax. There are direct descendants such as C++ and Objective-C. There are also more distantly related languages, including Java and JavaScript, that have no compatibility with, but still ape, many aspects of C’s syntax. If you are familiar with any of these languages, you will recognize most of the basic language features we are about to explore.

We saw the basic structure of a program in Chapter 1. In this chapter, I will be looking just at code inside methods. C# requires a certain amount of structure: code is made up of statements that live inside a method, which belongs to a type, which is typically inside a namespace, all inside a file that is part of a Visual Studio project contained by a solution. For clarity, most of the examples in this chapter will show the code of interest in isolation, as in Example 2-1.

Example 2-1. The code, ...

Get Programming C# 5.0 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.