0
0
C Sharp (C#)programming~5 mins

Implicit typing with var keyword in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Implicit typing lets the computer figure out the type of a variable for you. This makes your code shorter and easier to read.

When you want to write less code and avoid repeating the type name.
When the type is obvious from the value you assign, like numbers or strings.
When working with complex types like collections or LINQ queries.
When you want to keep your code clean and simple.
When the exact type is long or complicated to write.
Syntax
C Sharp (C#)
var variableName = value;

The var keyword tells the compiler to figure out the type from the value on the right side.

You must assign a value when you declare a var variable, so the type can be determined.

Examples
The compiler knows number is an int because 10 is an integer.
C Sharp (C#)
var number = 10;
The compiler knows name is a string because of the quotes.
C Sharp (C#)
var name = "Alice";
The compiler knows list is a List<string> from the right side.
C Sharp (C#)
var list = new List<string>();
Sample Program

This program shows how var automatically sets the type for different variables. It prints the values to the screen.

C Sharp (C#)
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var age = 25;
        var city = "New York";
        var scores = new List<int> { 90, 85, 88 };

        Console.WriteLine($"Age: {age}");
        Console.WriteLine($"City: {city}");
        Console.WriteLine("Scores:");
        foreach (var score in scores)
        {
            Console.WriteLine(score);
        }
    }
}
OutputSuccess
Important Notes

You cannot declare a var variable without assigning a value.

Once the type is set by the compiler, you cannot change it later.

Using var does not mean the variable is dynamically typed; the type is fixed at compile time.

Summary

Implicit typing with var lets the compiler decide the variable type.

It makes code shorter and easier to read when the type is clear from the value.

You must assign a value when declaring a var variable.