C# > Core C# > Variables and Data Types > Type Inference with var

Implicitly Typed Local Variables with 'var'

This snippet demonstrates how to use the var keyword in C# to declare variables with implicitly inferred types. var allows the compiler to determine the variable's type based on the expression used to initialize it. This can simplify code and improve readability in many cases. However, it's important to understand the limitations and best practices associated with using var.

Basic Usage of 'var'

The var keyword instructs the compiler to infer the type of the variable based on the initializer. In the code above, message is inferred to be a string, number is inferred to be an int, and pi is inferred to be a double. The compiler performs this inference at compile time, and the variable behaves exactly as if its type was explicitly declared.

var message = "Hello, World!"; // Compiler infers string type
var number = 42; // Compiler infers int type
var pi = 3.14159; // Compiler infers double type

Console.WriteLine(message);
Console.WriteLine(number);
Console.WriteLine(pi);

Concepts Behind the Snippet

Type inference is a feature where the compiler automatically deduces the data type of a variable without requiring the programmer to explicitly declare it. The var keyword enables this functionality in C#. The type is determined at compile time, so there is no runtime overhead associated with using var. The inferred type becomes fixed after compilation.

Real-Life Use Case

Using var is particularly useful when working with complex types or when the type is obvious from the initialization. For example, when iterating over a collection, using var simplifies the code while maintaining clarity. The example shows that iterating over a List is simpler if using var, and more readable.

var customers = new List<string> {"Alice", "Bob", "Charlie"};

foreach (var customer in customers)
{
    Console.WriteLine("Customer: " + customer);
}

Best Practices

  • Use var when the type is obvious from the initialization.
  • Avoid var when the type is not immediately clear, as it can reduce code readability.
  • var can only be used for local variables; it cannot be used for class fields or method parameters.
  • var requires initialization; you cannot declare a var variable without assigning a value.

Interview Tip

Be prepared to discuss the advantages and disadvantages of using var. Understand that var does not mean 'variant' or 'dynamic'. The type is still statically determined at compile time. Also, know when it is appropriate and not appropriate to use var to maintain code readability.

When to Use Them

Use var when:

  • The type is obvious from the right-hand side of the assignment.
  • Working with LINQ queries where the return type can be complex.
  • Iterating over collections with well-defined types.
Avoid var when:
  • The type is not immediately apparent from the initialization.
  • Declaring variables used across a large scope where explicit typing aids readability.

Memory Footprint

The memory footprint of a variable declared with var is the same as if the type was explicitly declared. Type inference occurs at compile time, so the compiler determines the appropriate data type and allocates memory accordingly. There is no runtime overhead or difference in memory usage.

Alternatives

The alternative to using var is to explicitly declare the type of the variable, such as string message = "Hello, World!";. Explicit typing can enhance code readability, especially when the type is not immediately obvious from the initialization.

Pros

  • Reduces verbosity in code.
  • Improves readability when the type is obvious.
  • Facilitates working with anonymous types and LINQ queries.

Cons

  • Can decrease readability if the type is not immediately apparent.
  • May lead to unintended type conversions if not used carefully.

FAQ

  • Can I use var for class-level fields?

    No, var can only be used for local variables declared within methods or blocks.
  • Does var make my code dynamically typed?

    No, var results in statically typed code. The type is inferred at compile time and cannot change at runtime.
  • What happens if I don't initialize a var variable?

    You will get a compile-time error. var requires initialization during declaration.