Skip to content

C# Basic Syntax

This chapter will detail the basic syntax of C#, including variables, data types, operators, constants, and other core concepts, laying a solid foundation for subsequent learning.

Variables and Identifiers

Variable Declaration

In C#, variables must be declared before use:

csharp
// Basic variable declaration syntax
data_type variable_name;
data_type variable_name = initial_value;

// Examples
int age;                    // Declare integer variable
string name = "Alice";      // Declare and initialize string variable
double salary = 5000.50;    // Declare and initialize double-precision floating point
bool isActive = true;       // Declare and initialize boolean variable

Variable Initialization

csharp
// Initialize at declaration (recommended)
int count = 0;
string message = "Hello";

// Declare first, then assign
int number;
number = 42;

// Multiple variables declared simultaneously
int x, y, z;
int a = 1, b = 2, c = 3;

// Use var keyword (type inference)
var temperature = 25.5;     // Inferred as double
var city = "Beijing";       // Inferred as string
var isReady = false;        // Inferred as bool

Identifier Naming Rules

csharp
// Valid identifiers
int age;
string firstName;
double _salary;
bool $isReady;
int camelCase;
int PascalCase;

// Invalid identifiers
// int 2age;        // Cannot start with number
// string class;      // Cannot use reserved keyword
// double my-var;    // Cannot use hyphen
// bool @class;      // Can use @ prefix for keywords (not recommended)

Naming Conventions:

  • Camel Case: firstName, lastName (for local variables and parameters)
  • Pascal Case: FirstName, LastName (for classes, methods, properties)
  • Underscore Prefix: _privateField (for private fields)
  • Constants: MAX_VALUE, PI (all uppercase)

Data Types

Value Types

Integer Types

csharp
// Signed integers
sbyte smallNumber = 127;        // 8-bit (-128 to 127)
short mediumNumber = 32767;     // 16-bit (-32,768 to 32,767)
int normalNumber = 2147483647;   // 32-bit (-2,147,483,648 to 2,147,483,647)
long bigNumber = 9223372036854775807L; // 64-bit

// Unsigned integers
byte tinyNumber = 255;           // 8-bit (0 to 255)
ushort smallUnsigned = 65535;     // 16-bit (0 to 65,535)
uint normalUnsigned = 4294967295U;  // 32-bit (0 to 4,294,967,295)
ulong bigUnsigned = 18446744073709551615UL; // 64-bit

Floating Point Types

csharp
float singlePrecision = 3.14f;    // 32-bit, 7 digits precision
double doublePrecision = 3.14159265359; // 64-bit, 15-16 digits precision
decimal financial = 1234.56m;      // 128-bit, 28-29 digits precision

Other Value Types

csharp
bool isReady = true;               // Boolean (true/false)
char grade = 'A';                  // 16-bit Unicode character
DateTime now = DateTime.Now;        // Date and time
TimeSpan duration = TimeSpan.FromHours(2); // Time interval

Reference Types

String Type

csharp
string greeting = "Hello, World!";
string empty = "";
string multiline = @"This is a
multiline string";

// String interpolation
string name = "Alice";
int age = 25;
string message = $"My name is {name} and I'm {age} years old.";

Arrays

csharp
// Single-dimensional array
int[] numbers = new int[5];
int[] scores = { 90, 85, 78, 92, 88 };

// Multi-dimensional array
int[,] matrix = new int[3, 3];
int[,] grid = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

// Jagged array
int[][] jagged = new int[3][];
jagged[0] = new int[] {1, 2, 3};
jagged[1] = new int[] {4, 5};
jagged[2] = new int[] {6, 7, 8, 9};

Object Type

csharp
object obj = 42;                    // Boxing integer
object str = "Hello";               // String is already reference type
obj = new List<int>();             // Reference to list

// Unboxing
int number = (int)obj;             // Must cast to original type

Type Conversion

Implicit Conversion

csharp
// Automatic conversion when no data loss
int intValue = 100;
long longValue = intValue;          // int to long (safe)
double doubleValue = intValue;       // int to double (safe)

// From smaller to larger type
byte b = 100;
short s = b;                     // byte to short
int i = s;                        // short to int

Explicit Conversion

csharp
// Requires casting, may cause data loss
double doubleValue = 123.456;
int intValue = (int)doubleValue;      // 123 (decimal part lost)

long bigNumber = 123456789L;
int smallNumber = (int)bigNumber;   // May overflow

// Safe conversion methods
string strNumber = "123";
int number = int.Parse(strNumber);     // Throws exception if invalid
int safeNumber = Convert.ToInt32(strNumber); // Handles null gracefully

// TryParse for safe conversion
string input = "456";
if (int.TryParse(input, out int result))
{
    Console.WriteLine($"Converted successfully: {result}");
}
else
{
    Console.WriteLine("Conversion failed");
}

Constants

const Keyword

csharp
// Compile-time constants
const int MAX_USERS = 100;
const double PI = 3.14159;
const string APP_NAME = "MyApplication";

// Must be initialized at declaration
const int DEFAULT_PORT = 8080;

// Cannot be modified
// MAX_USERS = 200;  // Error: Cannot assign to constant

readonly Keyword

csharp
class Configuration
{
    // Runtime constants
    public readonly string ConnectionString;
    public readonly DateTime CreatedAt;
    
    public Configuration(string connectionString)
    {
        ConnectionString = connectionString;  // Can be set in constructor
        CreatedAt = DateTime.Now;
    }
    
    public void UpdateConnection()
    {
        // ConnectionString = "new value";  // Error: Cannot modify readonly
    }
}

Operators

Arithmetic Operators

csharp
int a = 10, b = 3;

int sum = a + b;        // 13
int difference = a - b;   // 7
int product = a * b;      // 30
int quotient = a / b;      // 3 (integer division)
int remainder = a % b;      // 1 (modulus)

// Compound assignment
a += b;  // a = a + b
a -= b;  // a = a - b
a *= b;  // a = a * b
a /= b;  // a = a / b
a %= b;  // a = a % b

// Increment and decrement
int x = 5;
x++;      // x = 6 (post-increment)
++x;      // x = 7 (pre-increment)
x--;      // x = 6 (post-decrement)
--x;      // x = 5 (pre-decrement)

Comparison Operators

csharp
int a = 10, b = 20;

bool isEqual = (a == b);     // false
bool notEqual = (a != b);    // true
bool greater = (a > b);       // false
bool less = (a < b);         // true
bool greaterEqual = (a >= b);  // false
bool lessEqual = (a <= b);    // true

Logical Operators

csharp
bool x = true, y = false;

bool andResult = x && y;      // false (logical AND)
bool orResult = x || y;       // true (logical OR)
bool notResult = !x;          // false (logical NOT)

// Short-circuit evaluation
bool result = (a > 0) && (b > 0); // Second condition not evaluated if first is false

Bitwise Operators

csharp
int a = 5;  // Binary: 0101
int b = 3;  // Binary: 0011

int andResult = a & b;   // 1 (0001)
int orResult = a | b;    // 7 (0111)
int xorResult = a ^ b;    // 6 (0110)
int notResult = ~a;        // -6 (two's complement)
int leftShift = a << 1;    // 10 (1010)
int rightShift = a >> 1;   // 2 (0010)

Comments

Single Line Comments

csharp
// This is a single line comment
int age = 25; // Comment after code

Multi-line Comments

csharp
/*
 * This is a multi-line comment
 * It can span multiple lines
 * Useful for detailed explanations
 */
string name = "Alice";

XML Documentation Comments

csharp
/// <summary>
/// Calculates the area of a rectangle
/// </summary>
/// <param name="width">The width of the rectangle</param>
/// <param name="height">The height of the rectangle</param>
/// <returns>The area of the rectangle</returns>
public double CalculateRectangleArea(double width, double height)
{
    return width * height;
}

Nullable Types

Nullable Value Types

csharp
// Nullable syntax
int? nullableInt = null;
double? nullableDouble = 3.14;
bool? nullableBool = null;

// Check for value
if (nullableInt.HasValue)
{
    int value = nullableInt.Value;
}

// Null-coalescing operator
int result = nullableInt ?? 0;  // Use 0 if null

// Nullable arithmetic
int? a = 10;
int? b = 20;
int? sum = a + b;  // null if either operand is null

Nullable Reference Types (C# 8.0+)

csharp
// Enable nullable reference types
#nullable enable

string nonNullString = "Hello";    // Non-nullable
string? nullString = null;         // Nullable

// Warning suppression
string! definitelyNotNull = nullString!;  // Tell compiler it's not null

Summary

In this chapter, you learned:

  • Variable declaration and initialization
  • Identifier naming rules and conventions
  • C# data types (value types and reference types)
  • Type conversion (implicit and explicit)
  • Constants (const and readonly)
  • Operators (arithmetic, comparison, logical, bitwise)
  • Comments and documentation
  • Nullable types

These fundamental concepts form the foundation of C# programming. In the next chapter, we'll explore control structures to add logic and flow control to your programs.

Content is for learning and research only.