C# var Keyword with Example

In this tutorial, we will learn about the var keyword, its usage, syntax, and example in C#. By IncludeHelp Last updated : April 04, 2023

C# var Keyword

In C#, the var Keyword is used to declare an implicit type variable, which specifies the type of a variable based on initialized value.

Syntax

var variable_name = value;

Example of var keyword in C#

using System;
using System.Text;

namespace Test {
  class Program {
    static void Main(string[] args) {
      var a = 10;
      var b = 10.23;
      var c = 10.23f;
      var d = 10.23m;
      var e = 'X';
      var f = "Hello";

      Console.WriteLine("value of a {0}, type {1}", a, a.GetType());
      Console.WriteLine("value of b {0}, type {1}", b, b.GetType());
      Console.WriteLine("value of c {0}, type {1}", c, c.GetType());
      Console.WriteLine("value of d {0}, type {1}", d, d.GetType());
      Console.WriteLine("value of e {0}, type {1}", e, e.GetType());
      Console.WriteLine("value of f {0}, type {1}", f, f.GetType());

      //hit ENTER to exit
      Console.ReadLine();
    }
  }
}

Output

value of a 10, type System.Int32
value of b 10.23, type System.Double
value of c 10.23, type System.Single
value of d 10.23, type System.Decimal
value of e X, type System.Char
value of f Hello, type System.String




Comments and Discussions!

Load comments ↻






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