TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Implicitly Typed Local Variable

C# Implicitly Typed Local Variables for beginners and professionals with examples on overloading, method overriding, inheritance, aggregation, base, polymorphism, sealed, abstract, interface, namespaces, exception handling, file io, collections, multithreading, reflection etc.

<< Back to C-SHARP

C# Implicitly Typed Local Variable

In C#, we can create local variable without specifying its type. The C# var keyword is used to create implicit typed local variables. The C# compiler infers the types of variable on the basis of assigned value.

The var keyword can be used in following context.

  • To create local variables inside a method block.
  • In loop construct to initialize variable.
  • In using statement to store resource reference.

The var keyword has following restrictions.

  • It should use to declare and initialize local variable in the same statement.
  • It cannot be used to declare class variables.
  • It cannot be used to initialize multiple implicitly-typed variables in the same statement.
  • It cannot be used in initialization expression. Ex. var a = (a=220);

Let's see an example. Here, we have created integer, string and array type local variables.


C# Implicit Typed Local Variable Example

using System;
namespace CSharpFeatures
{
    class ImplicitTypedExample
    {
        public static void Main()
        {
            // integer
            var a = 20;
            // string
            var s = "TheDeveloperBlog";
            // array
            var arr = new[] { 1,2,3};  
            Console.WriteLine(a);
            Console.WriteLine(s);
            Console.WriteLine(arr[2]);
        }
    }
}

Output:

20
TheDeveloperBlog
3





Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf