Variables & Data Types
C# variables need an explicit type: int age = 21;.
Example: explicit type vs. var
using System;
class Program {
static void Main() {
string name = "Ada";
var age = 21;
Console.WriteLine($"{name} is {age} years old.");
}
}
Ada is 21 years old.
var lets the compiler infer the type from the assigned
value — age is still genuinely an int here,
fixed at compile time, just written without spelling the type out
explicitly. This is different from a dynamically-typed language: it's
purely a shorthand for the compiler to figure out what you clearly meant,
not permission for the variable to hold a different type later.
using System;
class Program {
static void Main() {
string name = "Ada";
int age = 21;
Console.WriteLine($"{name} is {age} years old.");
}
}
Ada is 21 years old.