DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited 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 = Program.GetAList();

        // `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}");
    }

    public static List<int> GetAList() => new List<int> { 1, 2, 3, 4, 5 };
}
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 (3)

Collapse
 
tinussmit profile image
Tinus Smit

Your List<int> example has zero ambiguity on the right of the equals, thus var could apply here as well 🤔

Did you mean something like:

List<int> numbers = GetNumbersFromElsewhere();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
juarezasjunior profile image
Juarez Júnior

You are right! Thank you for your message! I changed the example.

Collapse
 
therealbadri profile image
Mahmood Elbadri

Great pov