Menu
Coddy logo textTech

Var

Part of the Fundamentals section of Coddy's C# journey — lesson 10 of 69.

In C#, var is a keyword that allows you to declare a variable without explicitly specifying its type. The compiler infers the type of the variable based on the value assigned to it. This is known as type inference.

var can make code more concise and readable, especially when dealing with complex types.

Here's how you use var:

var age = 30;
var price = 99.99;
var name = "Alice";
var isActive = true;

In these examples, the compiler infers that age is an int, price is a double, name is a string, and isActive is a bool.

challenge icon

Challenge

Beginner

Write a C# program that declares and initializes the following variables using var:

  • A variable named quantity with the value 5.
  • A variable named itemPrice with the value 24.99.
  • A variable named productName with the value "Laptop".
  • A variable named isAvailable with the value true.

Cheat sheet

The var keyword allows you to declare variables without explicitly specifying their type. The compiler uses type inference to determine the type based on the assigned value:

var age = 30;        // inferred as int
var price = 99.99;   // inferred as double
var name = "Alice";  // inferred as string
var isActive = true; // inferred as bool

Try it yourself

using System;

public class Program {
    public static void Main(string[] args) {
        // Write code here
        
        
        // Don't change below
        Console.WriteLine("Quantity: " + quantity);
        Console.WriteLine("Item Price: " + itemPrice);
        Console.WriteLine("Product Name: " + productName);
        Console.WriteLine("Is Available: " + isAvailable);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals