C# Keywords Tutorial Part 95: var

C# Keywords Tutorial Part 95: var

Developers like C# because it is a robust programming language with a wide range of capabilities. The “var” keyword is one such feature that enables type inference and improves code readability. This blog article will discuss the C# “var” keyword and offer some code examples to demonstrate how to use it.

What is the “var” keyword?

A shortcut for defining a variable without explicitly stating its type is the “var” keyword. Instead, the type is deduced from the expression that is being used to declare the variable. Local variables, for loop variables, and LINQ query results may all be utilized with the “var” keyword.

Code Examples

Let’s take a look at some code examples to see how the “var” keyword is used in C#.

Example 1: Declaring a Local Variable

Here’s an example of how to declare a local variable using the “var” keyword:

var myString = "Hello, world!";

In this example, we’re declaring a variable called “myString” and using the “var” keyword to indicate that the type should be inferred. The value of the variable is a string literal, so the compiler infers that the variable should be of type “string”.

Example 2: Using the “var” Keyword in a For Loop

The “var” keyword can also be used in a for loop to infer the type of the loop variable:

var numbers = new[] { 1, 2, 3, 4, 5 };

foreach (var number in numbers)
{
    Console.WriteLine(number);
}

In this example, we’re declaring an array of integers called “numbers” and using the “var” keyword to infer the type of the loop variable in the foreach loop. The loop variable “number” is inferred to be of type “int” because “numbers” is an array of integers.

Example 3: Using the “var” Keyword with LINQ

The “var” keyword can also be used with LINQ to infer the type of the query result:

var fruits = new[] { "apple", "banana", "cherry", "date" };

var shortFruits = from fruit in fruits
                  where fruit.Length < 6
                  select fruit;

foreach (var fruit in shortFruits)
{
    Console.WriteLine(fruit);
}

In this example, we’re declaring an array of strings called “fruits” and using the “var” keyword to infer the type of the query result in the LINQ query. The query returns only the fruits that have a length of less than 6 characters, and the loop variable “fruit” is inferred to be of type “string”.

Benefits of the “var” Keyword

Using the “var” keyword has several benefits. It reduces the amount of typing required to declare variables, which can improve code readability and reduce the risk of errors. It can also make code more concise, especially when declaring complex or lengthy variable types. Additionally, using the “var” keyword can make it easier to refactor code, as the type of the variable can be changed without having to change every reference to the variable in the code.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *