C# Implicitly Typed Local Variables (var) with Example

In this tutorial, we will learn about the implicitly typed local variables, how to declare them with the help of examples in C#. By IncludeHelp Last updated : April 07, 2023

What is Implicitly Typed Local Variable?

In the normal variable declarations, we have to define their data types along with the variable name but using implicit we do not need to define the data type.

It is a special type of variable, which does not need to define data type. We can declare an implicit type variable by using var keyword, the type of variable is identified at the time of compilation depending upon the value assigned to it.

Implicitly Typed Local Variables Declarations

var x = 100;        // x is of type int.
var s = "Hello";    // s is of type string
var f = 3.14 f;     // f is of type float  
var y;              // invalid

In this process of declaring a variable without assigning a value is not possible.

C# Implicitly Typed Local Variables Example 1

In this example, we are declaring and initializing int, single, and decimal types implicitly typed local variables. And, printing the types of all declared variables.

using System;

class TypesDemo {
  static void Main() {
    var x = 10;
    Console.WriteLine(x.GetType());

    var f = 3.14f;;
    Console.WriteLine(f.GetType());

    var d = 3.14m;
    Console.WriteLine(d.GetType());
  }
}

Output

System.Int32
System.Single
System.Decimal
Press any key to continue . . .

Explanation

In above program x, f, d there are three different variables. They declared using var keyword but depending on assigning values they understand their types. For more clarity we are printing their types by using GetType() method.

C# Implicitly Typed Local Variables Example 2

In this example, we are declaring and initializing int, string, double, and boolean types implicitly typed local variables. And, printing the types of all declared variables.

using System;

public class Program {
  // Main method 
  static public void Main() {
    // Declaring and initializing 
    // implicitly typed variables 
    var intvar = 108;
    var strVar = "Hello, World!";
    var doubleVar = 36.24d;
    var boolVar = true;

    // Display the type of the variables 
    Console.WriteLine("Type of 'intvar' is : {0} ", intvar.GetType());
    Console.WriteLine("Type of 'strVar' is : {0} ", strVar.GetType());
    Console.WriteLine("Type of 'doubleVar' is : {0} ", doubleVar.GetType());
    Console.WriteLine("Type of 'boolVar' is : {0} ", boolVar.GetType());
    
    Console.ReadLine();
  }
}

Output

Type of 'intvar' is : System.Int32 
Type of 'strVar' is : System.String 
Type of 'doubleVar' is : System.Double 
Type of 'boolVar' is : System.Boolean



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.