DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Use var for Obvious Types, but Prefer Explicit Types for Ambiguous Types

Let’s talk about the use of var for Obvious Types, a practice that helps reduce code verbosity without sacrificing clarity.

In C#, var allows the compiler to infer the variable type, which reduces the need for repetitive declarations. However, using var indiscriminately can make the code harder to read, especially when the type isn’t immediately clear. Therefore, it’s recommended to use var only when the type is obvious from the expression. In cases where the type isn’t clear (e.g., objects from APIs or complex method calls), it’s better to declare the type explicitly.

This practice helps keep the code concise without sacrificing readability, especially in projects where many developers need to understand the code quickly.

Example:

public class Program
{
    public static void Main()
    {
        // Obvious type, good use of var
        var total = 100;

        // Prefer explicit type to avoid ambiguity
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // `decimal` with `var` is evident by the value
        var amount = 100.0m;

        Console.WriteLine($"Total: {total}");
        Console.WriteLine($"First number: {numbers[0]}");
        Console.WriteLine($"Amount: {amount}");
    }
}
Enter fullscreen mode Exit fullscreen mode

In the example, we use var for variables where the type is obvious, like int and decimal, simplifying the code. For variables where the type is less obvious (like a list of numbers), we choose to declare the type explicitly. This balance allows for cleaner code without sacrificing clarity.

Source code: GitHub

Top comments (0)