.NET Course
  • Welcome developers
  • LINQ
    • Advanced c# overview
      • Implicit typing
      • Generics
      • Attributes
      • Reflection
      • Delegates
      • Anonymous Methods and Lambda Expressions
      • Events
      • Anonymous Types
      • Ref vs Out
      • Task
      • TaskFactory
      • Asynchronous programming with async and await
      • Abstract class VS Interface
      • Inheritance, Composition and Aggregation in C#
    • LINQ Tutorial
      • Loading Related Entities
      • Lambda Expression
      • Standard Query Operators
    • Testing ASP.NET Core
      • Implementing unit tests for ASP.NET Core Web APIs
    • Software development principles
      • Object-Oriented Programming (Principles)
      • N-tier architecture style
      • Command and Query Responsibility Segregation (CQRS) pattern
      • SOLID: The First 5 Principles of Object Oriented Design
  • Helping links
    • SonarQube installation and tutorial for .net core projects
  • C# .NET Interview Questions
    • Ultimate C# Interview questions
      • Part 4
      • Part 3
      • Part 2
      • Part 1
  • Unit test .NET Core xUnit & MOQ
    • Content
      • Snippets
      • Traits
Powered by GitBook
On this page

Was this helpful?

  1. LINQ
  2. Advanced c# overview

Implicit typing

PreviousAdvanced c# overviewNextGenerics

Last updated 3 years ago

Was this helpful?

Local variables can be declared without giving an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET class library. For more information about how to initialize arrays with var, see .

The following examples show various ways in which local variables can be declared with var:

// i is compiled as an int
var i = 5;

// s is compiled as a string
var s = "Hello";

// a is compiled as int[]
var a = new[] { 0, 1, 2 };

// expr is compiled as IEnumerable<Customer>
// or perhaps IQueryable<Customer>
var expr =
    from c in customers
    where c.City == "London"
    select c;

// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };

// list is compiled as List<int>
var list = new List<int>();

var vs other types

If we declare a variable var without initializing it we will have an error because the compiler will not allow us to. Also, if we assign a null value to var variable, we will also have an error too.

var test = (string)null; // This is possible
var test = null; // ERROR
var test; // ERROR
var sb = new StringBuilder(); // This is possible
Implicitly Typed Arrays