Essential C# 5.0 Note - Chapter One - Introducing C#

keywords

  • Part of a larger, more complex execution platform called the Common Language Infrastructure (CLI), C# is a programming language for building software components and applications.
Note:

C# is a case-sensitive language:
Incorrect case prevents the code from compiling successfully.
  • The C# compiler allows any file extension for files containing C# source code, but .cs is typically used. After saving the source code to a file, developers must compile it.
Set up CSC to compile C# source code.

Set PATH=%PATH%;%Windir%\Microsoft.NET\Framework\v4.0.30319
  • The program created by the C# compiler, HelloWorld.exe, is an assembly.

    Instead of creating an entire program that can be executed independently, developers can create a library of code that can be referenced by another, larger program.

    Libraries (or class libraries) use the filename extension .dll, which stands for Dynamic Link Library (DLL).

    A library is also an assembly. In other words, the output from a successful C# compile is an assembly regardless of whether it is a program or a library.

  • Keywords

keywords

After C# 1.0, no new reserved keywords were introduced to C#. However, some constructs in later versions use contextual keywords, which are significant only in specific locations. Outside these designated locations, contextual keywords have no special significance

  • Rules for naming identifiers

    Ultimately, select clear, possibly even verbose names—especially when working on a team or when developing a library against which others will program.

    Two basic casing formats for an identifier:

    • Pascal case (henceforth PascalCase)

      capitalizes the first letter of each word in an identifier name

    • Camel case (henceforth camelCase)

      capitalizes the first letter of each word in an identifier name, except that the first letter is lowercase

      Guidelines:

      1. DO favor clarity over brevity when naming identifiers.

      2. DO NOT use abbreviations or contractions within identifier names.

      3. DO NOT use any acronyms unless they are widely accepted,
        and even then, only when necessary.

Guidelines:
1. DO capitalize both characters in two-character acronyms, 
except for the first word of a camelCased identifier.

2. DO capitalize only the first character in acronyms with three or more characters, 
except for the first word of a camelCased identifier.

3. DO NOT capitalize any of the characters in acronyms 
at the beginning of a camelCased identifier.

4. DO NOT use Hungarian notation 
(that is, do not encode the type of a variable in its name).

Although it is rare, keywords may be used as identifiers if they include “@” as a prefix. e.g.”name a local variable @return”, “name a method @throw()”.

  • Type Definition

    All executable code in C# appears within a type definition, and the most common type definition begins with the keyword class. A class definition is the section of code that generally begins with class identifier { … }

class HelloWorld
{
//...
}

Class name can be vary, but must be PascalCase.

Guidelines

1. DO name classes with nouns or noun phrases.

2. DO use PascalCasing for all class names.

Generally, programs contain multiple types, each containing multiple methods.

  • Method

    A method in C# is

    A named block of code introduced by a method declaration and (usually) followed by zero or more statements within curly braces.

    1. Perform computations and/or actions.

    2. Provide a means of structuring and organizing code so that it is more readable.

    3. More importantly, can be reused and called from multiple places, and so avoid the need to duplicate code.

    4. The method declaration introduces the method and defines the method name along with the data passed to and from the method.

  • Main Method

    1. The location where C# programs begin execution is the Main method, which begins with static void Main().

    2. Although the Main method declaration can vary to some degree, static and the method name, Main, are always required for a program.

    3. C# requires that the Main method return either void or int, and that it take either no parameters, or a single array of strings.

    4. The args parameter is an array of strings corresponding to the command-line arguments. However, the first element of the array is not the program name but the first command-line parameter to appear after the executable name.

    5. The int returned from Main is the status code and it indicates the success of the program’s execution. A return of a nonzero value generally indicates an error.

static int Main(string[] args)
{

//...
}
  • Statements and Statement Delimiters

    System.Console.WriteLine(), which is used to write a line of text to the console.
    C# generally uses a semicolon to indicate the end of a statement, where a statement comprises one or more actions that the code will perform.

    • Statements without Semicolons
    1. One example that does not include the semicolon is a switch statement.
      Because curly braces are always included in a switch statement, C# does not require a semicolon following the statement.

    2. In fact, code blocks themselves are considered statements (they are also composed of statements) and they don’t require closure using a semicolon.

    3. Similarly, there are cases, such as the using declarative, in which a semicolon occurs at the end but it is not a statement.

  • Place multiple statements on the same line

    Since creation of a newline does not separate statements, you can place multiple statements on the same line and the C# compiler will interpret the line to have multiple instructions.
static int Main(string[] args)
{

System.Console.WriteLine("Up");System.Console.WriteLine("Down");
}
  • Splitting of a statement across multiple lines

C# also allows the splitting of a statement across multiple lines. Again, the C# compiler looks for a semicolon to indicate the end of a statement

static int Main(string[] args)
{

System.Console.WriteLine(
"Hello. My name is Inigo Montoya.");
}
Beginner Topic: What Is Whitespace?

Whitespace is the combination of one or more consecutive formatting characters such as tab, space, and newline characters.
Eliminating all whitespace between words is obviously significant, as is whitespace within a quoted string.

The semicolon makes it possible for the C# compiler to ignore whitespace in code.
Apart from a few exceptions, C# allows developers to insert whitespace throughout the code without altering its semantic meaning.

  • Working with Variables

keywords

Beginner Topic: Local Variables

A variable refers to a storage location by a name that the program can later assign and modify.Local indicates that the programmer declared the variable within a method.

To declare a variable is to define it, which you do by

  1. Specifying the type of data which the variable will contain
  2. Assigning it an identifier (name)
  • Data Types

Beginner Topic: What Is a Data Type?

The type of data that a variable declaration specifies is called a data type (or object type). A data type, or simply type, is a classification of things that share similar characteristics and behavior.

Similarly, in programming languages, a type is a definition for several items endowed with similar qualities.

  • Declaring a Variable

It is possible to declare multiple variables within the same statement by specifying the data type once and separating each identifier with a comma.

string message1, message2;

  • In C#, the name of the variable may begin with any letter or an underscore (_), followed by any number of letters, numbers, and/or underscores.

  • By convention, however, local variable names are camelCased (the first letter in each word is capitalized, except for the first word) and do not include underscores.

Guidelines
  DO use camelCasing for local variables.
  • Assigning a Variable

After declaring a local variable, you must assign it a value before reading from it. One way to do this is to use the = operator, also known as the simple assignment operator.

Operators are symbols used to identify the function the code is to perform.

class MiracleMax
{
static void Main()
{

// declaring 'valerie'
string valerie;

// declaring and assigning a variable to 'max'
string max = "Have fun storming the castle!";

// assigning a variable to 'valerie'
valerie = "Think it will work?";

System.Console.WriteLine(max);
System.Console.WriteLine(valerie);
max = "It would take a miracle.";

System.Console.WriteLine(max);
}
}
  • Assign a variable as part of the variable declaration (as it was for max),
  • Assign a variable afterward in a separate statement (as with the variable valerie)
  • The value assigned must always be on the right side.

C# requires that local variables be determined by the compiler to be “definitely assigned” before they are read.

Additionally, an assignment returns a value. Therefore, C# allows two assignments within the same statement,

class MiracleMax
{
static void Main()
{

// ...
string requirements, max;
requirements = max = "It would take a miracle.";
// ...
}
}
  • Using a Variable

The result of the assignment, is that you can then refer to the value using the variable identifier.

Advanced Topic: Strings Are Immutable

All data of type string, whether string literals or otherwise, is immutable (or unmodifiable). For example, it is not possible to change the string “Come As You Are” to “Come As You Age.” A change such as this requires that you reassign the variable to point to a new location in memory, instead of modifying the data to which the variable originally referred.
  • Console Input and Output

Advanced Topic: System.Console.Read()

In addition to the System.Console.ReadLine() method, there is also a System.Console.Read() method.

However, the data type returned by the System.Console.Read() method is an integer corresponding to the character value read, or –1 if no more characters are available.

To retrieve the actual character, it is necessary to first cast the integer to a character.

int readValue;
char character;
readValue = System.Console.Read();
character = (char) readValue;
System.Console.Write(character);
  • The System.Console.Read() method does not return the input until the user presses the Enter key

  • no processing of characters will begin, even if the user types multiple characters before pressing the Enter key.

In C# 2.0, there appears a new method called System.Console.ReadKey() which, in contrast to System.Console.Read(), returns the input after a single keystroke.
It allows the developer to intercept the keystroke and perform actions such as key validation, restricting the characters to numerics.

System.Console.WriteLine(
"Your full name is {0} {1}.", firstName, lastName);

writes out the entire output using composite formatting. With composite formatting, the code first supplies a format string to define the output format. It identifies two indexed placeholders for data insertion in the string.

  • Comments

Comments