SyntaxStudy
Sign Up
C# Declaring Variables and Constants
C# Beginner 1 min read

Declaring Variables and Constants

In C#, every variable must have a declared type, either written explicitly or inferred with `var`. Local variables must be assigned before use; the compiler enforces definite assignment. Constants declared with `const` are compile-time literals, whereas `readonly` fields are evaluated once at construction time and can hold run-time values. C# 9 introduced records and init-only properties, and C# 10 added `record struct`. These immutable-by-default types make it easy to model data without accidental mutation. The `with` expression creates a copy of a record with selected properties changed, preserving the original. Naming conventions in C# follow Microsoft's guidelines: PascalCase for types and public members, camelCase for local variables and parameters, and `_camelCase` for private fields. The compiler is case-sensitive, so `count` and `Count` are distinct identifiers.
Example
// Variables, constants, and readonly members in C#

// Explicitly typed
int    age     = 25;
string firstName = "Alice";
double salary  = 75_000.50;   // digit separators improve readability

// Type-inferred (still statically typed)
var city    = "London";
var numbers = new List<int> { 1, 2, 3 };

// Constant — must be a compile-time literal
const double TaxRate = 0.20;
const string AppName = "MyApp";

// Readonly field — evaluated at construction, immutable afterwards
public class Config
{
    public readonly DateTime StartTime = DateTime.UtcNow;
    public const int MaxRetries = 3;
}

// Record — immutable value-object with built-in equality
record Point(double X, double Y);

var p1 = new Point(1.0, 2.0);
var p2 = p1 with { Y = 5.0 };   // non-destructive mutation
Console.WriteLine(p1);  // Point { X = 1, Y = 2 }
Console.WriteLine(p2);  // Point { X = 1, Y = 5 }

// Tuple variables (no need for a named type)
var coordinates = (Latitude: 51.5, Longitude: -0.1);
Console.WriteLine($"Lat: {coordinates.Latitude}");

// Deconstruction
var (lat, lon) = coordinates;
Console.WriteLine($"Lon: {lon}");