Juarez Júnior
Posted on November 8, 2024
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 };
}
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
Posted on November 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 26, 2024