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
BeginnerWrite a C# program that declares and initializes the following variables using var:
- A variable named
quantitywith the value5. - A variable named
itemPricewith the value24.99. - A variable named
productNamewith the value"Laptop". - A variable named
isAvailablewith the valuetrue.
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 boolTry 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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3