Implicitly Typed Local Variables - C# Tutorial
C# Course / Version Features / Implicitly Typed Local Variables

Implicitly Typed Local Variables

BLUF: Mastering Implicitly Typed Local Variables is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: Implicitly Typed Local Variables

C# is a powerful, modern language for enterprise solutions. Discover how Implicitly Typed Local Variables enhances your development workflow in the guide below.

In C#, it is possible to define a local variable without explicitly mentioning its data type. The var keyword in C# is employed for declaring implicitly typed local variables. The compiler in C# deduces the variable types based on the assigned values.

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 consider an illustration. In this case, we've generated local variables of integer, string, and array data types.

C# Implicit Typed Local Variable Example

Example

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

Output:

Output

20
hello world
3

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience