C# in A Nutshell - Code Listings - 3
C# in A Nutshell - Code Listings - 3
Syntax Basics
Type Basics
Predefined Type Examples
int x = 2015;
message = message + x.ToString();
Console.WriteLine (message); // Hello world2015
int y = 5000;
bool lessThanAMile = y < 5280;
if (lessThanAMile)
Console.WriteLine ("This will print");
// Just as we can build complex functions from simple functions, we can build complex types
// from primitive types. UnitConverter serves a a blueprint for unit conversions:
Console.WriteLine (Panda.Population); // 2
https://www.albahari.com/nutshell/E12-CH02.aspx 1/4
4/18/24, 1:15 AM C# in a Nutshell - Code Listings
Defining a namespace
using Animals;
namespace Animals
{
public class Panda
{
public string Name;
using System;
class Program
{
static void Main() // Program entry point
{
int x = 12 * 30;
Console.WriteLine (x);
}
}
Conversions
// Implicit conversions are allowed when the compiler can guarantee they will
// always succeed and no information is lost in conversion:
x.Dump ("x");
y.Dump ("y");
z.Dump ("z");
Value Types
Console.WriteLine (p1.X); // 7
Console.WriteLine (p2.X); // 7
Console.WriteLine (p1.X); // 9
Console.WriteLine (p2.X); // 7
Reference Types
// A reference type has two parts: an object and the reference to that object.
https://www.albahari.com/nutshell/E12-CH02.aspx 2/4
4/18/24, 1:15 AM C# in a Nutshell - Code Listings
Point p1 = new Point();
p1.X = 7;
Console.WriteLine (p1.X); // 7
Console.WriteLine (p2.X); // 7
Console.WriteLine (p1.X); // 9
Console.WriteLine (p2.X); // 9
Null
// A reference can be assigned the literal null, indicating that the reference points to nothing:
Point p = null;
Console.WriteLine (p == null); // True
Storage Overhead
struct Point
{
int x; // 4 bytes
int y; // 4 bytes
}
// However, the CLR requires that fields are offset within the type at an address
// that’s a multiple of their size:
struct A
{
byte b; // 1 byte
long l; // 8 bytes
}
Numeric Types
Arrays
Null Operators
https://www.albahari.com/nutshell/E12-CH02.aspx 3/4
4/18/24, 1:15 AM C# in a Nutshell - Code Listings
Statements
Namespaces
C# 12
in a Nutshell
About the Book
Code Listings
C# 12 in a Nutshell
C# 10 in a Nutshell
C# 9.0 in a Nutshell
C# 8.0 in a Nutshell
C# 7.0 in a Nutshell
Extras
Contact
https://www.albahari.com/nutshell/E12-CH02.aspx 4/4