C#
Beginner
1 min read
Declaring Variables and Constants
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}");