C# lets you declare local variables without giving them explicit types. It is possible with the help of the “var” type variable.
The “var” keyword is used to declare a var type variable. The var type variable can be used to store a simple .NET data type, a complex type, an anonymous type, or a user-defined type.
When we declare a variable as a var type, the variable's type is inferred from the initialization at compile time.
When to use var
- Use of “var” is not recommended everywhere. The var was created to handle declarations when the type is not known, such as generic types, lamdas, and query expressions. If you already know the type of a variable, you must declare that explicitly. Remember, if you don’t declare a variable explicitly, the compiler must do extra work to determine the type. While the cost of this operation may not be significant, it’s just unnecessary burden on the compiler.
- Don’t use var for simple local variable types that are known to you.
- Use of var when you’re not sure what type of data will be stored in a variable.
- Use in anonymous types and anonymous collections.
- Use of var improves code readability. Use when class names are extremely long.
- Imported unmanaged code types that doesn’t follow naming conventions.
0 comments:
Post a Comment