DEV Community

mohamed Tayel
mohamed Tayel

Posted on

C# Clean Code: using var guide lines

C# is known for being a strongly typed language, where each variable’s type must be declared. However, there's an exception: implicitly typed variables, which can be declared using the var keyword. This feature can simplify your code, making it easier to read.

What Does var Do?

When you use var, you’re not declaring a variant; instead, you’re instructing the C# compiler to determine the variable’s type based on the right-hand side of the assignment. This inferred type can be:

  • Built-in types (e.g., int, string)
  • Anonymous types
  • User-defined types
  • .NET library types

Example 1: Basic Use of var

var number = Convert.ToInt32(Console.ReadLine());
var message = "Welcome to C#";
Enter fullscreen mode Exit fullscreen mode

Here:

  • number is inferred as int because of the Convert.ToInt32 method.
  • message is inferred as string.

However, if the input from the console is not an integer, an exception will be thrown. To avoid this, use int.TryParse:

if(int.TryParse(Console.ReadLine(), out var number))
{
    Console.WriteLine($"Parsed number: {number}");
}
else
{
    Console.WriteLine("Invalid input. Please enter a number.");
}
Enter fullscreen mode Exit fullscreen mode

This example ensures the variable can only be assigned if the input is a valid integer, preventing exceptions.

When to Use var for Better Readability

  • Use var when the type is obvious from the right-hand side, like:
  var welcomeMessage = "Hello, World!";
  var sum = 25 + 30;
Enter fullscreen mode Exit fullscreen mode

Here, the inferred types are string and int, respectively.

  • Avoid using var when the type is not clear or when it compromises readability:
  // Not recommended
  var x = GetUserInput(); 

  // Better alternative
  string userInput = GetUserInput();
Enter fullscreen mode Exit fullscreen mode

Example 2: Use Descriptive Names

// Not clear
var x = 'A';

// More readable
char letter = 'A';
Enter fullscreen mode Exit fullscreen mode

A Note on Unsigned Types

C# allows both signed (int) and unsigned (uint) integers. It’s generally better to use int for consistency and better compatibility across libraries:

// Avoid this
uint unsignedNumber = 10;

// Prefer this
int number = 10;
Enter fullscreen mode Exit fullscreen mode

Arrays in C

Arrays are essential but need to be used thoughtfully. While they’re convenient, other collections like List or Dictionary might be better suited for complex scenarios.

Example 3: Initializing Arrays

  1. Concise Syntax
   string[] vowels = { "A", "E", "I", "O", "U" };
Enter fullscreen mode Exit fullscreen mode

Here, we define and initialize the array in one line.

  1. Explicit Instantiation
   var numbers = new int[] { 1, 2, 3, 4, 5 };
Enter fullscreen mode Exit fullscreen mode

You can use var here because the type is clear from the instantiation.

  1. Specifying Size
   int[] scores = new int[3];
   scores[0] = 85;
   scores[1] = 90;
   scores[2] = 95;
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

  • Use var when the type is clear and improves readability.
  • Be mindful of exceptions when using var with user input.
  • Use arrays wisely, favoring concise syntax when initializing them, and explore other collections as needed for better flexibility.

This approach ensures better readability, maintainability, and consistency in your C# code.

Top comments (0)