By Joseph Albahari, Ben Albahari
Price: $49.99 USD
£30.99 GBP
Cover | Table of Contents | Forum
ToString method.ToString method.
Func<int,int> square = x => x * x;
Console.WriteLine (square(3)); // 9
string[] names = { "Tom", "Dick", "Harry" };
IEnumerable<string> filteredNames = // Include only names
Enumerable.Where (names, n => n.Length >= 4); // of >= 4 characters.
string[] names = { "Tom", "Dick", "Harry" };
IEnumerable<string> filteredNames = names.Where (n => n.Length >= 4);
using System; // importing namespace
class Test // class declaration
{
static void Main ( ) // method declaration
{
int x = 12 * 30; // statement 1
Console.WriteLine (x); // statement 2
} // end of method
} // end of class
int x = 12 * 30;
Console.WriteLine (x);
12 * 30 and stores the result in a local variable, named x, which is an integer type. The second statement calls the Console class's WriteLine method, to print the variable x to a text window on the screen.Main:
static void Main ( )
{
...
}
using System;
class Test
{
static void Main ( )
{
Console.WriteLine (FeetToInches (30)); // 360
Console.WriteLine (FeetToInches (100)); // 1200
}
static int FeetToInches (int feet)
{
int inches = feet * 12;
return inches;
}
}
FeetToInches that has a parameter for inputting feet, and a return type for outputting inches:static int InchesToFeet (int feet ) {...}
30 and 100 are the arguments passed to the FeetToInches method. The
using System; // importing namespace
class Test // class declaration
{
static void Main ( ) // method declaration
{
int x = 12 * 30; // statement 1
Console.WriteLine (x); // statement 2
} // end of method
} // end of class
int x = 12 * 30;
Console.WriteLine (x);
12 * 30 and stores the result in a local variable, named x, which is an integer type. The second statement calls the Console class's WriteLine method, to print the variable x to a text window on the screen.Main:
static void Main ( )
{
...
}
using System;
class Test
{
static void Main ( )
{
Console.WriteLine (FeetToInches (30)); // 360
Console.WriteLine (FeetToInches (100)); // 1200
}
static int FeetToInches (int feet)
{
int inches = feet * 12;
return inches;
}
}
FeetToInches that has a parameter for inputting feet, and a return type for outputting inches:static int InchesToFeet (int feet ) {...}
30 and 100 are the arguments passed to the FeetToInches method. The Main method in our example has empty parentheses because it has no parameters, and is
using System;
class Test
{
static void Main ( )
{
int x = 12 * 30;
Console.WriteLine (x);
}
}
System Test Main x Console WriteLine
myVariable ), and all other identifiers should be in Pascal case (e.g., MyMethod ).using class static void int
abstract | As | base | bool | break |
byte | Case | catch | char | checked |
class | Const | continue | decimal | default |
delegate | Do | double | else | enum |
event | Explicit | extern | false | finally |
fixed | Float | for | foreach | goto |
if | Implicit | in | int | interface |
internal | Is | lock | long | namespace |
new | Null | object | operator | out |
override | Params | private | protected | public |
readonly | ref | return | sbyte | sealed |
short | sizeof | stackalloc | static | string |
struct | switch | this | throw | true |
try | typeof | uint | ulong | unchecked |
unsafe | ushort | using | virtual | void |
while |
@ prefix. For instance:
class class {...} // illegal
class @class {...} // legal
@ symbol doesn't form part of the identifier itself. So @myVariable is the same as myVariable.add | ascending | by | descending | equals |
from | get | global | group | in |
into | join | let | on | orderby |
partial | remove | select | set | value |
var | where | yield |
x in our first program:
static void Main ( )
{
int x = 12 * 30;
Console.WriteLine (x);
}
x is int.int type is a predefined primitive type for representing the set of integers that fit into 32 bits of memory, from −231 to 231−1. We can perform functions such as arithmetic with instances of the int type as follows:int x = 12 * 30;
string type. The string type represents a sequence of characters, such as ".NET" or "". We can manipulate strings by calling functions on them as follows:string message = "Hello world"; string upperMessage = message.ToUpper( ); Console.WriteLine (upperMessage); // HELLO WORLD int x = 2007; message = message + x.ToString( ); Console.WriteLine (message); // Hello world2007
bool type has exactly two possible values: true and false. The bool type is commonly used to conditionally branch execution flow based with an if statement. For example:
bool simpleVar = false;
if (simpleVar)
Console.WriteLine ("This will not print");
int x = 5000;
bool lessThanAMile = x < 5280;
if (lessThanAMile)
Console.WriteLine ("This will print");
System namespace in the .NET Framework contains many important types that are not predefined by C# (e.g., DateTime ).UnitConverter —a class that serves as a blueprint for unit conversions:C# type | System type | Suffix | Category | Size | Range | Notes |
|---|---|---|---|---|---|---|
sbyte | SByte | Integral | 8 bits | −27 to 27−1 | ||
short | Int16 | Integral | 16 bits | −215 to 215−1 | ||
int | Int32 | Integral | 32 bits | -231 to 231−1 | ||
long | Int64 | L | Integral | 64 bits | −263 to 263−1 | |
byte | Byte | Integral | 8 bits | 0 to 28−1 | Unsigned | |
ushort | UInt16 | Integral | 16 bits | 0 to 216−1 | Unsigned | |
uint | UInt32 | U | Integral | 32 bits | 0 to 232−1 | Unsigned |
ulong | UInt64 | UL | Integral | 64 bits | 0 to 264−1 | Unsigned |
float | Single | F | Real | 32 bits | ±∼10−45 to ∼1038 | Single-precision |
double | Double | D | Real | 64 bits | ±∼10−324 to ∼10308 | Double-precision |
decimal | Decimal | M | Real | 128 bits | ±∼10−28 to ∼1028 | Base 10 |
int and long are first-class citizens and are favored by both C# and the runtime. The other integral types are typically used for interoperability or when space efficiency is paramount.float and double are called floating-point types and are typically used for scientific calculations. The decimal type is typically used for financial calculations, where base-10-accurate arithmetic and high precision are required.0x prefix. For example:int x = 127; long y = 0x7F;
double d = 1.5; double million = 1E06;
double or an integral type:E), it is a double.int, uint, ulong, and long.Console.WriteLine ( 1.0.GetType( )); // Double (double) Console.WriteLine ( 1E06.GetType( )); // Double (double) Console.WriteLine ( 1.GetType( )); // Int32 (int) Console.WriteLine ( 0xF0000000.GetType( )); // UInt32 (uint)
bool type (aliasing the System.Boolean type) is a logical value that can be assigned the literal true or false.bool array uses two bytes of memory. The System.Collections.BitArray class can be used where the storage efficiency of one bit per boolean value is required.bool type to numeric types or vice versa.== and != test for equality and inequality of any type, but always return a bool value. Value types typically have a very simple notion of equality:int x = 1; int y = 2; int z = 1; Console.WriteLine (x == y); // False Console.WriteLine (x == z); // True
public class Dude
{
public string Name;
public Dude (string n) { Name = n; }
}
Dude d1 = new Dude ("John");
Dude d2 = new Dude ("John");
Console.WriteLine (d1 == d2); // False
Dude d3 = d1;
Console.WriteLine (d1 == d3); // True
<, >, >=, and <=, work for all numeric types, but should be used with caution with real numbers (see the "" section earlier in this chapter). The comparison operators also work on enum type members, by comparing their underlying integral values. This is described in the "" section in .&& and || operators test for and and or conditions. They are frequently used in conjunction with the ! operator, which expresses not. In this example, the UseUmbrella method returns true if it's rainy or sunny (to protect us from the rain or the sun), as long as it's not also windy (since umbrellas are useless in the wind):
static bool UseUmbrella (bool rainy, bool sunny, bool windy)
{
return ! windy && (rainy || sunny);
}
char type (aliasing the System.Char type) represents a Unicode character and occupies two bytes. A char literal is specified inside single quotes:char c = 'A'; // simple character
char newLine = '\n'; char backSlash = '\\';
Char | Meaning | Value |
|---|---|---|
\' | Single quote | 0x0027 |
\" | Double quote | 0x0022 |
\\ | Backslash | 0x005C |
\0 | Null | 0x0000 |
\a | Alert | 0x0007 |
\b | Backspace | 0x0008 |
\f | Form feed | 0x000C |
\n | New line | 0x000A |
\r | Carriage return | 0x000D |
\t | Horizontal tab | 0x0009 |
\v | Vertical tab | 0x000B |
\u (or \x) escape sequence lets you specify any Unicode character via its four-digit hexadecimal code.char copyrightSymbol = '\u00A9'; char omegaSymbol = '\u03A9'; char newLine = '\u000A';
char to a numeric type works for the numeric types that can accommodate an unsigned short. For other numeric types, an explicit conversion is required.System.String type, covered in depth in ) represents an immutable sequence of Unicode characters. A string literal is specified inside double quotes:string a = "Heat";
string is a reference type, rather than a value type. However, since a string is immutable, it takes on value-like semantics.char literals also work inside strings:string a = "Blah blah.\n";
string a1 = "\\\\server\\fileshare\\helloworld.cs";
string literals. A verbatim string literal is prefixed with @ and does not support escape sequences. The following verbatim string is identical to the preceding one:
string a2 = @ "\\server\fileshare\helloworld.cs";
string escaped = "First Line\r\nSecond Line"; string verbatim = @"First Line Second Line"; Console.WriteLine (escaped == verbatim); // True
char[] vowels = new char[5]; // Declare an array of 5 characters
vowels [0] = 'a'; vowels [1] = 'e'; vowels [2] = 'i'; vowels [3] = 'o'; vowels [4] = 'u'; Console.WriteLine (vowels [1]); // e
for loop statement to iterate through each element in the array. The for loop in this example cycles the integer i from 0 to 4:for (int i = 0; i < vowels.Length; i++) Console.Write (vowels [i]); // aeiou
Length property of an array returns the number of elements in the array. Once an array has been created, its length cannot be changed. The System.Collection namespace and subnamespaces provide higher-level data structures, such as dynamically sized arrays and dictionaries.
char[] vowels = new char[] {'a','e','i','o','u'};
System.Array class, providing common services for all arrays. These members include methods to get and set elements regardless of the array type, and are described in the section "" in .int is a value type, this allocates 1,000 integers in one contiguous block of memory. The default value for each element will be 0:int[] a = new int[1000]; Console.Write (a[123]); // 0
static int Factorial (int x)
{
if (x == 0) return 1;
return x * Factorial (x-1);
}
int is allocated on the stack, and each time the method exists, the int is deallocated.StringBuilder objects, referenced by the variables ref1 and ref2. The variable ref3 is then assigned to the object referenced by ref2. Next, we assign both ref1 and ref2 to null. At this point, object1 (i.e., the first StringBuilder object created) is eligible for garbage collection, since nothing references it. In contrast, object2 (i.e., the second StringBuilder object created) is still referenced by ref3, so it is not eligible for garbage collection. When the Main method terminates, ref3 goes out of scope, and object2 becomes eligible for garbage collection.
using System;
using System.Text;
class Test
{
static void Main ( )
{
StringBuilder ref1 = new StringBuilder("object1");
StringBuilder ref2 = new StringBuilder("object2");
StringBuilder ref3 = ref2;
ref1 = ref2 = null;
Console.WriteLine(ref3); // object2
}
}
12
* operator to combine two operands (the literal expressions 12 and 30), as follows:12 * 30
(12 * 30) in the following example:1 + (12 * 30)
Math.Log (1)
. operator), and the second expression performs a method call (with the ( ) operator).Console.WriteLine (1)
1 + Console.WriteLine(1) // Compile-time error
= operator to assign the result of another expression to a variable. For example:x = x * 5
x and 10 to y:y = 5 * (x = 2)
a = b = c = d = 0
x *= 2 // equivalent to x = x * 2 x <<= 1 // equivalent to x = x << 1
{} tokens).string someWord = "rosebud"; int someNumber = 42; bool rich = true, famous = false;
const double c = 2.99792458E08; c+=10; // error
static void Main( )
{
int x;
{
int y;
int x; // error, x already defined
}
{
int y; // ok, y not in scope
}
Console.WriteLine(y); // error, y is out of scope
}
// declare variables with declaration statements: string s; int x, y; System.Text.StringBuilder sb; // expression statements x = 1 + 2; // assignment expression x++; // increment expression y = Math.Max(x, 5); // assignment expression Console.WriteLine(y); // method call expression sb = new StringBuilder( ); // assignment expression new StringBuilder( ); // object instantiation expression