← C# tutorial

C#

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.

Example
using System;

class Program {
    static void Main() {
        string name = "Ada";
        int age = 21;
        Console.WriteLine($"{name} is {age} years old.");
    }
}
Output
Ada is 21 years old.
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account