Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

C# - var

In C#, variables must be declared with the data type. These are called explicitly typed variables.

Example: Explicitly Typed Variable
int i = 100;// explicitly typed variable

C# 3.0 introduced var keyword to declare method level variables without specifying a data type explicitly.

Example: Implicitly Typed Local Variable
var j = 100; // implicitly typed local variable

The compiler will infer the type of a variable from the expression on the right side of the = operator. Above, var will be compiled as int.

The following infers the type from an expression.

Example: var from expression
int i = 10;
var j = i + 1; // compiles as int

var can be used to declare any built-in data type or a user-defined type or an anonymous type variable. The following example shows C# compiler infers type based on the value:

Example: Implicitly-Typed Variable
static void Main(string[] args)
{
    var i = 10;
    Console.WriteLine("Type of i is {0}", i.GetType());

    var str = "Hello World!!";
    Console.WriteLine("Type of str is {0}", str.GetType());

    var dbl = 100.50d;
    Console.WriteLine("Type of dbl is {0}", dbl.GetType());

    var isValid = true;
    Console.WriteLine("Type of isValid is {0}", isValid.GetType());

    var ano = new { name = "Steve" };
    Console.WriteLine("Type of ano is {0}", ano.GetType());

    var arr = new[] { 1, 10, 20, 30 };
    Console.WriteLine("Type of arr is {0}", arr.GetType());

    var file = new FileInfo("MyFile");
    Console.WriteLine("Type of file is {0}", file.GetType());

}
Try it

Implicitly-typed variables must be initialized at the time of declaration; otherwise C# compiler would give an error: Implicitly-typed variables must be initialized.

var i; // Compile-time error: Implicitly-typed variables must be initialized
i = 100;

Multiple declarations of var variables in a single statement are not allowed.

var i = 100, j = 200, k = 300; // Error: cannot declare var variables in a single statement

//The followings are also valid
var i = 100; 
var j = 200; 
var k = 300;

var cannot be used for function parameters.

void Display(var param) //Compile-time error
{
    Console.Write(param);
}

var can be used in for, and foreach loops.

for(var i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}

var can also be used with LINQ queries.

Example: LINQ Query Syntax in C#
// string collection
IList<string> stringList = new List<string>() { 
    "C# Tutorials",
    "VB.NET Tutorials",
    "Learn C++",
    "MVC Tutorials" ,
    "Java" 
};

// LINQ Query Syntax
var result = from s in stringList
            where s.Contains("Tutorials") 
            select s;
Try it
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.