Analysis of var keyword usage in C

  • 2020-12-07 04:11:01
  • OfStack

This paper analyzes the usage of var keyword in C#. Share to everybody for everybody reference. The specific methods are as follows:

The C# keyword comes with.NET 3.5, along with the anonymous function LINQ, which is inferred by the compiler. In general, using the var keyword is a prerequisite when a variable is local (not including class-level variables) and initialized at declaration time. When to use, and when not to use, the following is a personal opinion.

1. Use the var keyword when declaring anonymous functions

var temp = new {Name="", Category=""};

2. var keyword is used when LINQ projects the result of anonymous function

var temp = from p in products
        where p.Name =="sth"
        select new {p.Name, p.Category};

3. Use the var keyword when the type is clear

var string = ""    ;
var result = new List<Product>();

Above, you can obviously infer the type from the right hand side of the equal sign, and consider using the var keyword.

4. var keyword should be used with caution when the type is unclear

var result = ProductRepository.GetProducts();

Above, if you use the var keyword, it is one point less readable.

Hopefully this article has helped you with your C# programming.


Related articles: